问:
Customizing a TextBox to look like a textblock in UWP
I am new to XAML and Blend but here Is what I am trying to do. I am developing an application where I need to place a TextBox (or any input control ) but is shouldn't have the properties of a TextBox. Please refer the image below.

I want help to implement the below mentioned functionalities.

On TAP - It should let me edit the values, without highlighting the background area - the thing that usually TextBoxes do

I don't need any border

Once i stop editing and tap outside the control , it should look like a TextBlock, tapping it again let you edit normally

答:
You have to modify the default style of TextBox which you can find here.

You could end up with something like this:

```<code><Style x:Key="TransparentTextBox" TargetType="TextBox">
    <Setter Property="Background" Value="Transparent"/>
    <Setter Property="BorderBrush" Value="Transparent"/>
    <Setter Property="Template">
        <Setter.Value>
            <ControlTemplate TargetType="TextBox">
                <Grid>
                    <Grid.Resources>
                        <Style x:Name="DeleteButtonStyle" TargetType="Button">
                            <Setter Property="Template">
                                <Setter.Value>
                                    <ControlTemplate TargetType="Button">
                                        <Grid x:Name="ButtonLayoutGrid" BorderBrush="{ThemeResource TextBoxButtonBorderThemeBrush}"
                                                      BorderThickness="{TemplateBinding BorderThickness}"
                                                      Background="{ThemeResource TextBoxButtonBackgroundThemeBrush}"
                                                >
                                            <VisualStateManager.VisualStateGroups>
                                                <VisualStateGroup x:Name="CommonStates">
                                                    <VisualState x:Name="Normal"/>
                                                    <VisualState x:Name="PointerOver">
                                                        <Storyboard>
                                                            <ObjectAnimationUsingKeyFrames Storyboard.TargetName="GlyphElement" Storyboard.TargetProperty="Foreground">
                                                                <DiscreteObjectKeyFrame KeyTime="0" Value="{ThemeResource SystemControlHighlightAccentBrush}"/>
                                                            </ObjectAnimationUsingKeyFrames>
                                                        </Storyboard>
                                                    </VisualState>
                                                    <VisualState x:Name="Pressed">
                                                        <Storyboard>
                                                            <ObjectAnimationUsingKeyFrames Storyboard.TargetName="ButtonLayoutGrid" Storyboard.TargetProperty="Background">
                                                                <DiscreteObjectKeyFrame KeyTime="0" Value="{ThemeResource SystemControlHighlightAccentBrush}"/>
                                                            </ObjectAnimationUsingKeyFrames>
                                                            <ObjectAnimationUsingKeyFrames Storyboard.TargetName="GlyphElement" Storyboard.TargetProperty="Foreground">
                                                                <DiscreteObjectKeyFrame KeyTime="0" Value="{ThemeResource SystemControlHighlightAltChromeWhiteBrush}"/>
                                                            </ObjectAnimationUsingKeyFrames>
                                                        </Storyboard>
                                                    </VisualState>
                                                    <VisualState x:Name="Disabled">
                                                        <Storyboard>
                                                            <DoubleAnimation Storyboard.TargetName="ButtonLayoutGrid" Storyboard.TargetProperty="Opacity" To="0" Duration="0"/>
                                                        </Storyboard>
                                                    </VisualState>
                                                </VisualStateGroup>
                                            </VisualStateManager.VisualStateGroups>

                                            <TextBlock x:Name="GlyphElement"
                                                       Foreground="{ThemeResource SystemControlForegroundChromeBlackMediumBrush}"
                                                       VerticalAlignment="Center"
                                                       HorizontalAlignment="Center"
                                                       FontStyle="Normal"
                                                       FontSize="12"
                                                       Text=""
                                                       FontFamily="{ThemeResource SymbolThemeFontFamily}"
                                                       AutomationProperties.AccessibilityView="Raw"
                                                       />
                                        </Grid>
                                    </ControlTemplate>
                                </Setter.Value>
                            </Setter>
                        </Style>
                    </Grid.Resources>
                    <VisualStateManager.VisualStateGroups>
                        <VisualStateGroup x:Name="CommonStates">
                            <VisualState x:Name="Normal"/>
                            <VisualState x:Name="PointerOver"/>
                            <VisualState x:Name="Focused"/>
                            <VisualState x:Name="Disabled"/>
                        </VisualStateGroup>
                        <VisualStateGroup x:Name="ButtonStates">
                            <VisualState x:Name="ButtonVisible">
                                <Storyboard>
                                    <ObjectAnimationUsingKeyFrames Storyboard.TargetName="DeleteButton" Storyboard.TargetProperty="Visibility">
                                        <DiscreteObjectKeyFrame KeyTime="0">
                                            <DiscreteObjectKeyFrame.Value>
                                                <Visibility>Visible</Visibility>
                                            </DiscreteObjectKeyFrame.Value>
                                        </DiscreteObjectKeyFrame>
                                    </ObjectAnimationUsingKeyFrames>
                                </Storyboard>
                            </VisualState>
                            <VisualState x:Name="ButtonCollapsed"/>
                        </VisualStateGroup>
                    </VisualStateManager.VisualStateGroups>

                    <Grid.ColumnDefinitions>
                        <ColumnDefinition Width="*"/>
                        <ColumnDefinition Width="Auto"/>
                    </Grid.ColumnDefinitions>
                    <Grid.RowDefinitions>
                        <RowDefinition Height="Auto"/>
                        <RowDefinition Height="*"/>
                    </Grid.RowDefinitions>

                    <Border x:Name="BackgroundElement"
                            Grid.Row="1"
                            Background="{TemplateBinding Background}"
                            Margin="{TemplateBinding BorderThickness}"
                            Opacity="{ThemeResource TextControlBackgroundRestOpacity}"
                            Grid.ColumnSpan="2"
                            Grid.RowSpan="1"
                            />
                    <Border x:Name="BorderElement"
                            Grid.Row="1"
                            BorderBrush="{TemplateBinding BorderBrush}"
                            BorderThickness="{TemplateBinding BorderThickness}"
                            Grid.ColumnSpan="2"
                            Grid.RowSpan="1"
                            />
                    <ContentPresenter x:Name="HeaderContentPresenter"
                                      x:DeferLoadStrategy="Lazy"
                                      Visibility="Collapsed"
                                      Grid.Row="0"
                                      Foreground="{ThemeResource SystemControlForegroundBaseHighBrush}"
                                      Margin="0,0,0,8"
                                      Grid.ColumnSpan="2"
                                      Content="{TemplateBinding Header}"
                                      ContentTemplate="{TemplateBinding HeaderTemplate}"
                                      FontWeight="Normal"
                                      />
                    <ScrollViewer x:Name="ContentElement"
                                  Grid.Row="1"
                                  HorizontalScrollMode="{TemplateBinding ScrollViewer.HorizontalScrollMode}"
                                  HorizontalScrollBarVisibility="{TemplateBinding ScrollViewer.HorizontalScrollBarVisibility}"
                                  VerticalScrollMode="{TemplateBinding ScrollViewer.VerticalScrollMode}"
                                  VerticalScrollBarVisibility="{TemplateBinding ScrollViewer.VerticalScrollBarVisibility}"
                                  IsHorizontalRailEnabled="{TemplateBinding ScrollViewer.IsHorizontalRailEnabled}"
                                  IsVerticalRailEnabled="{TemplateBinding ScrollViewer.IsVerticalRailEnabled}"
                                  IsDeferredScrollingEnabled="{TemplateBinding ScrollViewer.IsDeferredScrollingEnabled}"
                                  Margin="{TemplateBinding BorderThickness}"
                                  Padding="{TemplateBinding Padding}"
                                  IsTabStop="False"
                                  AutomationProperties.AccessibilityView="Raw"
                                  ZoomMode="Disabled"
                                  />
                    <ContentControl x:Name="PlaceholderTextContentPresenter"
                                    Grid.Row="1"
                                    Foreground="{ThemeResource SystemControlPageTextBaseMediumBrush}"
                                    Margin="{TemplateBinding BorderThickness}"
                                    Padding="{TemplateBinding Padding}"
                                    IsTabStop="False"
                                    Grid.ColumnSpan="2"
                                    Content="{TemplateBinding PlaceholderText}"
                                    IsHitTestVisible="False"
                                    />
                    <Button x:Name="DeleteButton"
                            Grid.Row="1"
                            Style="{StaticResource DeleteButtonStyle}"
                            BorderThickness="{TemplateBinding BorderThickness}"
                            Margin="{ThemeResource HelperButtonThemePadding}"
                            IsTabStop="False"
                            Grid.Column="1"
                            Visibility="Collapsed"
                            FontSize="{TemplateBinding FontSize}"
                            MinWidth="34"
                            VerticalAlignment="Stretch"
                            />
                </Grid>
            </ControlTemplate>
        </Setter.Value>
    </Setter>
</Style>
</code>```

Body:
You have to modify the default style of TextBox which you can find here.

You could end up with something like this:

<Style x:Key="TransparentTextBox" TargetType="TextBox">
    <Setter Property="Background" Value="Transparent"/>
    <Setter Property="BorderBrush" Value="Transparent"/>
    <Setter Property="Template">
        <Setter.Value>
            <ControlTemplate TargetType="TextBox">
                <Grid>
                    <Grid.Resources>
                        <Style x:Name="DeleteButtonStyle" TargetType="Button">
                            <Setter Property="Template">
                                <Setter.Value>
                                    <ControlTemplate TargetType="Button">
                                        <Grid x:Name="ButtonLayoutGrid" BorderBrush="{ThemeResource TextBoxButtonBorderThemeBrush}"
                                                      BorderThickness="{TemplateBinding BorderThickness}"
                                                      Background="{ThemeResource TextBoxButtonBackgroundThemeBrush}"
                                                >
                                            <VisualStateManager.VisualStateGroups>
                                                <VisualStateGroup x:Name="CommonStates">
                                                    <VisualState x:Name="Normal"/>
                                                    <VisualState x:Name="PointerOver">
                                                        <Storyboard>
                                                            <ObjectAnimationUsingKeyFrames Storyboard.TargetName="GlyphElement" Storyboard.TargetProperty="Foreground">
                                                                <DiscreteObjectKeyFrame KeyTime="0" Value="{ThemeResource SystemControlHighlightAccentBrush}"/>
                                                            </ObjectAnimationUsingKeyFrames>
                                                        </Storyboard>
                                                    </VisualState>
                                                    <VisualState x:Name="Pressed">
                                                        <Storyboard>
                                                            <ObjectAnimationUsingKeyFrames Storyboard.TargetName="ButtonLayoutGrid" Storyboard.TargetProperty="Background">
                                                                <DiscreteObjectKeyFrame KeyTime="0" Value="{ThemeResource SystemControlHighlightAccentBrush}"/>
                                                            </ObjectAnimationUsingKeyFrames>
                                                            <ObjectAnimationUsingKeyFrames Storyboard.TargetName="GlyphElement" Storyboard.TargetProperty="Foreground">
                                                                <DiscreteObjectKeyFrame KeyTime="0" Value="{ThemeResource SystemControlHighlightAltChromeWhiteBrush}"/>
                                                            </ObjectAnimationUsingKeyFrames>
                                                        </Storyboard>
                                                    </VisualState>
                                                    <VisualState x:Name="Disabled">
                                                        <Storyboard>
                                                            <DoubleAnimation Storyboard.TargetName="ButtonLayoutGrid" Storyboard.TargetProperty="Opacity" To="0" Duration="0"/>
                                                        </Storyboard>
                                                    </VisualState>
                                                </VisualStateGroup>
                                            </VisualStateManager.VisualStateGroups>

                                            <TextBlock x:Name="GlyphElement"
                                                       Foreground="{ThemeResource SystemControlForegroundChromeBlackMediumBrush}"
                                                       VerticalAlignment="Center"
                                                       HorizontalAlignment="Center"
                                                       FontStyle="Normal"
                                                       FontSize="12"
                                                       Text="&#xE10A;"
                                                       FontFamily="{ThemeResource SymbolThemeFontFamily}"
                                                       AutomationProperties.AccessibilityView="Raw"
                                                       />
                                        </Grid>
                                    </ControlTemplate>
                                </Setter.Value>
                            </Setter>
                        </Style>
                    </Grid.Resources>
                    <VisualStateManager.VisualStateGroups>
                        <VisualStateGroup x:Name="CommonStates">
                            <VisualState x:Name="Normal"/>
                            <VisualState x:Name="PointerOver"/>
                            <VisualState x:Name="Focused"/>
                            <VisualState x:Name="Disabled"/>
                        </VisualStateGroup>
                        <VisualStateGroup x:Name="ButtonStates">
                            <VisualState x:Name="ButtonVisible">
                                <Storyboard>
                                    <ObjectAnimationUsingKeyFrames Storyboard.TargetName="DeleteButton" Storyboard.TargetProperty="Visibility">
                                        <DiscreteObjectKeyFrame KeyTime="0">
                                            <DiscreteObjectKeyFrame.Value>
                                                <Visibility>Visible</Visibility>
                                            </DiscreteObjectKeyFrame.Value>
                                        </DiscreteObjectKeyFrame>
                                    </ObjectAnimationUsingKeyFrames>
                                </Storyboard>
                            </VisualState>
                            <VisualState x:Name="ButtonCollapsed"/>
                        </VisualStateGroup>
                    </VisualStateManager.VisualStateGroups>

                    <Grid.ColumnDefinitions>
                        <ColumnDefinition Width="*"/>
                        <ColumnDefinition Width="Auto"/>
                    </Grid.ColumnDefinitions>
                    <Grid.RowDefinitions>
                        <RowDefinition Height="Auto"/>
                        <RowDefinition Height="*"/>
                    </Grid.RowDefinitions>

                    <Border x:Name="BackgroundElement"
                            Grid.Row="1"
                            Background="{TemplateBinding Background}"
                            Margin="{TemplateBinding BorderThickness}"
                            Opacity="{ThemeResource TextControlBackgroundRestOpacity}"
                            Grid.ColumnSpan="2"
                            Grid.RowSpan="1"
                            />
                    <Border x:Name="BorderElement"
                            Grid.Row="1"
                            BorderBrush="{TemplateBinding BorderBrush}"
                            BorderThickness="{TemplateBinding BorderThickness}"
                            Grid.ColumnSpan="2"
                            Grid.RowSpan="1"
                            />
                    <ContentPresenter x:Name="HeaderContentPresenter"
                                      x:DeferLoadStrategy="Lazy"
                                      Visibility="Collapsed"
                                      Grid.Row="0"
                                      Foreground="{ThemeResource SystemControlForegroundBaseHighBrush}"
                                      Margin="0,0,0,8"
                                      Grid.ColumnSpan="2"
                                      Content="{TemplateBinding Header}"
                                      ContentTemplate="{TemplateBinding HeaderTemplate}"
                                      FontWeight="Normal"
                                      />
                    <ScrollViewer x:Name="ContentElement"
                                  Grid.Row="1"
                                  HorizontalScrollMode="{TemplateBinding ScrollViewer.HorizontalScrollMode}"
                                  HorizontalScrollBarVisibility="{TemplateBinding ScrollViewer.HorizontalScrollBarVisibility}"
                                  VerticalScrollMode="{TemplateBinding ScrollViewer.VerticalScrollMode}"
                                  VerticalScrollBarVisibility="{TemplateBinding ScrollViewer.VerticalScrollBarVisibility}"
                                  IsHorizontalRailEnabled="{TemplateBinding ScrollViewer.IsHorizontalRailEnabled}"
                                  IsVerticalRailEnabled="{TemplateBinding ScrollViewer.IsVerticalRailEnabled}"
                                  IsDeferredScrollingEnabled="{TemplateBinding ScrollViewer.IsDeferredScrollingEnabled}"
                                  Margin="{TemplateBinding BorderThickness}"
                                  Padding="{TemplateBinding Padding}"
                                  IsTabStop="False"
                                  AutomationProperties.AccessibilityView="Raw"
                                  ZoomMode="Disabled"
                                  />
                    <ContentControl x:Name="PlaceholderTextContentPresenter"
                                    Grid.Row="1"
                                    Foreground="{ThemeResource SystemControlPageTextBaseMediumBrush}"
                                    Margin="{TemplateBinding BorderThickness}"
                                    Padding="{TemplateBinding Padding}"
                                    IsTabStop="False"
                                    Grid.ColumnSpan="2"
                                    Content="{TemplateBinding PlaceholderText}"
                                    IsHitTestVisible="False"
                                    />
                    <Button x:Name="DeleteButton"
                            Grid.Row="1"
                            Style="{StaticResource DeleteButtonStyle}"
                            BorderThickness="{TemplateBinding BorderThickness}"
                            Margin="{ThemeResource HelperButtonThemePadding}"
                            IsTabStop="False"
                            Grid.Column="1"
                            Visibility="Collapsed"
                            FontSize="{TemplateBinding FontSize}"
                            MinWidth="34"
                            VerticalAlignment="Stretch"
                            />
                </Grid>
            </ControlTemplate>
        </Setter.Value>
    </Setter>
</Style>


来源: stackexchange

问:
Method that takes Input from user in C#
I'm switching to C# from C++ and I'm trying to learn the methods. Can you help me create a method that takes 2 variables as input from the user? In C++ it was pretty easy just making a void method and adding & before the variable's name like: void Input( int &a, int &b) which would save any changes in their value in the main function. Is there a way to do that in C#?

答:
In C# you can pass an argument by reference with the ref keyword. So you can define your method like:

```<code>public void Input (<b>ref</b> int foo, <b>ref</b> int bar) {
    foo = 14;
    bar = 25;
}</code>```

You call the method with the ref keyword as well:

```<code>int a = 0;
int b = 0;
Input(<b>ref</b> a, <b>ref</b> b);
// now a = 14 and b = 25</code>```

You this mention pass-by-reference explicitly (but the advantage is that syntactically it is clear that this is pass-by-reference).

ContentLicense: CC BY-SA 3.0

Title: Method that takes Input from user in C#

Body:
In C# you can pass an argument by reference with the ref keyword. So you can define your method like:

public void Input (ref int foo, ref int bar) {
    foo = 14;
    bar = 25;
}

You call the method with the ref keyword as well:

int a = 0;
int b = 0;
Input(ref a, ref b);
// now a = 14 and b = 25

You this mention pass-by-reference explicitly (but the advantage is that syntactically it is clear that this is pass-by-reference).


问:
this and protoype javascript
Why does  alert(d.prototype) return a undefined? Shouldn't the prototyope be animaL?</p>

```<code>function Dog(){

}
function Animal(){
    this.name = "name";
}
Dog.prototype = new Animal();
var d = new Dog();

alert(d.constructor);
alert(d.prototype);
alert(d.name);
</code>```

答:
You shouldn't use Dog.prototype = new Animal();
Try: Dog.prototype = Animal; instead.

ContentLicense: CC BY-SA 2.5

Title: this and protoype javascript

Body:
Why does  alert(d.prototype) return a undefined? Shouldn't the prototyope be animaL?

function Dog(){

}
function Animal(){
    this.name = "name";
}
Dog.prototype = new Animal();
var d = new Dog();

alert(d.constructor);
alert(d.prototype);
alert(d.name);


问:
Select specifics characters with jquery
I would like tu select the specifics characters cm in a specific div and add this in a span.

The html :

```<code><div class="fc_img_tooltip_desc" style="line-height:1em;">20X10cm
10X100
50X50
100X100</div>
</code>```

Jquery

```<code><script>
function highlight_words(cm , fc_img_tooltip_desc) {
if(keywords) {
    var textNodes;
    keywords = keywords.replace(/\W/g, '');
    var str = keywords.split(" ");
    $(str).each(function() {
        var term = this;
        var textNodes = $(element).contents().filter(function() { return
this.nodeType === 3 });
        textNodes.each(function() {
          var content = $(this).text();
          var regex = new RegExp(term, "gi");
          content = content.replace(regex, '<span class="highlight">' + term
+ '</span>');
          $(this).replaceWith(content);
        });
    });
}
}
$(window).onload(function(){ highlight_words(); });
</script>
</code>```

This don't work, i do something wrong.

What i have :

```<code><div class="fc_img_tooltip_desc" style="line-height:1em;">20X10cm
10X100cm
50X50cm
100X100cm</div>
</code>```

What i want:

```<code><div class="fc_img_tooltip_desc" style="line-height:1em;">20X10 cm
10X100 cm
50X50 cm
100X100 cm</div>
</code>```

答:
In jQuery, you can retrieve the text that had a [conversion unit] (in this case 'cm') using match() method.

```<code>// Check if [measurement] text's had a numeric pattern
// followed by any [conversion unit of cm]
var sMeasurementText = $.trim($('.fc_img_tooltip_desc').text());
var sMeasurementPattern = /^(?:\d+x\d+cm)/i;
console.log(sMeasurementText.match(sMeasurementPattern));
</code>```

from which it will return an [array] at hand like this:

```<code>["10x20cm", index: 0, input: "10x20cm 10X100 50X50 100X100"]
</code>```

Take note that this pattern will retrieve the '1st' string that matches that condition.

Here's a jsfiddle for further reference: http://jsfiddle.net/fh1hj690/

Hope this helps for your case.

Title: Select specifics characters with jquery

Body:
I would like tu select the specifics characters cm in a specific div and add this in a span.

The html :

20X10cm
10X100
50X50
100X100

Jquery

This don't work, i do something wrong.

What i have :

20X10cm
10X100cm
50X50cm
100X100cm

What i want:

20X10 cm
10X100 cm
50X50 cm
100X100 cm

Body:
In jQuery, you can retrieve the text that had a [conversion unit] (in this case 'cm') using match() method.

// Check if [measurement] text's had a numeric pattern
// followed by any [conversion unit of cm]
var sMeasurementText = $.trim($('.fc_img_tooltip_desc').text());
var sMeasurementPattern = /^(?:\d+x\d+cm)/i;
console.log(sMeasurementText.match(sMeasurementPattern));

from which it will return an [array] at hand like this:

["10x20cm", index: 0, input: "10x20cm 10X100 50X50 100X100"]

Take note that this pattern will retrieve the '1st' string that matches that condition.

Here's a jsfiddle for further reference: http://jsfiddle.net/fh1hj690/

Hope this helps for your case.


问:
Setting divider location on a JSplitPane
I'd like to have 3 resizable horizontally JPanels. It works fine but I can not set the position of the first JSlitPane: sp.setDividerLocation(.3); doesn't work.

```<code>public class JSplitPanelProva extends JFrame {

        public JSplitPanelProva() {
            this.setLayout(new BorderLayout());

            JPanel leftPanel = new JPanel();
            leftPanel.setBackground(Color.BLUE);
            JPanel centerPanel = new JPanel();
            centerPanel.setBackground(Color.CYAN);
            JPanel rightPanel = new JPanel();
            rightPanel.setBackground(Color.GREEN);

            JSplitPane sp = new JSplitPane(JSplitPane.HORIZONTAL_SPLIT, leftPanel, centerPanel);
            JSplitPane sp2 = new JSplitPane(JSplitPane.HORIZONTAL_SPLIT, sp, rightPanel);

            sp.setOneTouchExpandable(true);
            sp2.setOneTouchExpandable(true);

            this.add(sp2, BorderLayout.CENTER);

            this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

            this.setSize(1000, 600);
            this.setVisible(true);

            sp.setDividerLocation(.3);
            sp2.setDividerLocation(.6);
        }

        /**
         * @param args the command line arguments
         */
        public static void main(String[] args) {
            new JSplitPanelProva();

        }

    }
</code>```

I get this:

Can someone help me?
Thanks.

答:
Change:

```<code>        sp.setDividerLocation(.3);
        sp2.setDividerLocation(.6);
</code>```

To:

```<code>    sp2.setDividerLocation(.6);
    ActionListener splitListener = new ActionListener() {

        @Override
        public void actionPerformed(ActionEvent e) {
            sp.setDividerLocation(.3);
        }
    };
    Timer t = new Timer(200, splitListener);
    t.setRepeats(false);
    t.start();
</code>```

And it will work as expected. The delay gives time for the GUI to recalculate sizes.

Body:
I'd like to have 3 resizable horizontally JPanels. It works fine but I can not set the position of the first JSlitPane: sp.setDividerLocation(.3); doesn't work.

public class JSplitPanelProva extends JFrame {

        public JSplitPanelProva() {
            this.setLayout(new BorderLayout());

            JPanel leftPanel = new JPanel();
            leftPanel.setBackground(Color.BLUE);
            JPanel centerPanel = new JPanel();
            centerPanel.setBackground(Color.CYAN);
            JPanel rightPanel = new JPanel();
            rightPanel.setBackground(Color.GREEN);

            JSplitPane sp = new JSplitPane(JSplitPane.HORIZONTAL_SPLIT, leftPanel, centerPanel);
            JSplitPane sp2 = new JSplitPane(JSplitPane.HORIZONTAL_SPLIT, sp, rightPanel);

            sp.setOneTouchExpandable(true);
            sp2.setOneTouchExpandable(true);

            this.add(sp2, BorderLayout.CENTER);

            this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

            this.setSize(1000, 600);
            this.setVisible(true);

            sp.setDividerLocation(.3);
            sp2.setDividerLocation(.6);
        }

        /**
         * @param args the command line arguments
         */
        public static void main(String[] args) {
            new JSplitPanelProva();

        }

    }

I get this:

Can someone help me?
Thanks.

Body:
Change:

        sp.setDividerLocation(.3);
        sp2.setDividerLocation(.6);

To:

    sp2.setDividerLocation(.6);
    ActionListener splitListener = new ActionListener() {

        @Override
        public void actionPerformed(ActionEvent e) {
            sp.setDividerLocation(.3);
        }
    };
    Timer t = new Timer(200, splitListener);
    t.setRepeats(false);
    t.start();

And it will work as expected. The delay gives time for the GUI to recalculate sizes.


问:
fetch details of different students on the basis of Rank in a single query
I have a Student table like

```<code>STUDENT_NAME    MOBILE                  RANK
 RANJAN        1234567890                 2
 ABC           1234589077                 3
 XYZ           1234568888                 1
 PQR           1234567999                 4
</code>```

I want to fetch details of Maximum rank holder & Minimum rank holder student in a single query. How this possible ??

答: SELECT * FROM Student WHERE RANK=(SELECT MAX(RANK) FROM Student ) OR RANK=(SELECT MIN(RANK) FROM Student )</p>

Body:
I have a Student table like

STUDENT_NAME    MOBILE                  RANK
 RANJAN        1234567890                 2
 ABC           1234589077                 3
 XYZ           1234568888                 1
 PQR           1234567999                 4

I want to fetch details of Maximum rank holder & Minimum rank holder student in a single query. How this possible ??


问:
Java lesson: public void displayMessage() Doesn't working
I have a Java book and im trying to learn obviously Java Programming.

I have a lesson that tells me simply to put this Code on Eclipse.

I copied from the Book and i put it on Eclipse program that i test and learn there. When i run it, it doesn't says any error. But at the moment that i run it, it shows me this error:

Code on Eclipse

Code on the Book

Does anyone knows what happens here? Is the book wrong or what?

Thanks.

答:
You need to add main method to your class and call displayMessage() in it :

```<code>class GradeBook {

    public void displayMessage() {
        System.out.println("something");
    }

    public static void main(String[] args) {
        new GradeBook().displayMessage();
    }
}
</code>```

Body:
You need to add main method to your class and call displayMessage() in it :

class GradeBook {

    public void displayMessage() {
        System.out.println("something");
    }

    public static void main(String[] args) {
        new GradeBook().displayMessage();
    }
}


问:
ggplot alpha levels appear different on fill and border of points (ringing artefact)
I am plotting many points using ggplot with a constant  transparency value for all points.

What I find is that the circular points have a more transparent fill than their individual border, so that the borders are noticeably brighter than their fill (I'm plotting light circles on a dark background), i.e. there seems to be a ringing artefact.

The effect is that they look like rings rather than semi-transparent circles.

```<code>library(ggplot2)
set.seed(123)
data <- data.frame( x = sample(1:100,2000, replace=T),
                    y = sample(1:100,2000, replace=T) )
ggplot(data, aes(x,y)) +
  geom_point(alpha=0.2, color="dodgerblue", fill="dodgerblue", size=4) +
  theme(panel.background = element_rect(fill = 'black', colour = 'black'))
</code>```

I'm not sure why it does this, so information as to why this occurs would be great.

Possible solutions would be to make the border and fill the same transparency, or to make the border 100% transparent (setting the border to say, the background colour, would ruin the visuals when points overlap). I'm not sure how to do either of these.

答:
Given that you want disks with constant colour & opacity simplest thing to do that fixed it for me, also in the RStudio plot preview window is just to use option shape=16 :

```<code>data <- data.frame( x = sample(1:100,2000, replace=T),
                y = sample(1:100,2000, replace=T) )
ggplot(d, aes(x,y)) +
  geom_point(alpha=0.2, color="dodgerblue", size=5, shape=16) +
  theme(panel.background = element_rect(fill = 'black', colour = 'black'))
</code>```

Alternatively, shape=21 and a 100% semitransparent fill with
fill=adjustcolor("dodgerblue",alpha.f=0) also works:

```<code>ggplot(data, aes(x,y)) +
     geom_point(alpha=0.2, fill=adjustcolor("dodgerblue",alpha.f=0), size=5, shape=21) +
     theme(panel.background = element_rect(fill = 'black', colour = 'black'))
</code>```

Using stroke=0 as suggested in the currently accepted answer doesn't seem to resolve the problem entirely for me (ringing effect goes away a little bit but not entirely, this is on Windows at least) :

```<code>ggplot(data, aes(x,y)) +
    geom_point(alpha=0.2, colour="dodgerblue", fill="dodgerblue", stroke=0,  size=5) +
    theme(panel.background = element_rect(fill = 'black', colour = 'black'))
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I am plotting many points using ggplot with a constant  transparency value for all points.

What I find is that the circular points have a more transparent fill than their individual border, so that the borders are noticeably brighter than their fill (I'm plotting light circles on a dark background), i.e. there seems to be a ringing artefact.

The effect is that they look like rings rather than semi-transparent circles.

library(ggplot2)
set.seed(123)
data <- data.frame( x = sample(1:100,2000, replace=T),
                    y = sample(1:100,2000, replace=T) )
ggplot(data, aes(x,y)) +
  geom_point(alpha=0.2, color="dodgerblue", fill="dodgerblue", size=4) +
  theme(panel.background = element_rect(fill = 'black', colour = 'black'))

I'm not sure why it does this, so information as to why this occurs would be great.

Possible solutions would be to make the border and fill the same transparency, or to make the border 100% transparent (setting the border to say, the background colour, would ruin the visuals when points overlap). I'm not sure how to do either of these.

Body:
Given that you want disks with constant colour & opacity simplest thing to do that fixed it for me, also in the RStudio plot preview window is just to use option shape=16 :

data <- data.frame( x = sample(1:100,2000, replace=T),
                y = sample(1:100,2000, replace=T) )
ggplot(d, aes(x,y)) +
  geom_point(alpha=0.2, color="dodgerblue", size=5, shape=16) +
  theme(panel.background = element_rect(fill = 'black', colour = 'black'))

Alternatively, shape=21 and a 100% semitransparent fill with
fill=adjustcolor("dodgerblue",alpha.f=0) also works:

ggplot(data, aes(x,y)) +
     geom_point(alpha=0.2, fill=adjustcolor("dodgerblue",alpha.f=0), size=5, shape=21) +
     theme(panel.background = element_rect(fill = 'black', colour = 'black'))

Using stroke=0 as suggested in the currently accepted answer doesn't seem to resolve the problem entirely for me (ringing effect goes away a little bit but not entirely, this is on Windows at least) :

ggplot(data, aes(x,y)) +
    geom_point(alpha=0.2, colour="dodgerblue", fill="dodgerblue", stroke=0,  size=5) +
    theme(panel.background = element_rect(fill = 'black', colour = 'black'))


问:
i am stucking when i submitt my contact form
I have made a contact from... which is supposed to redirect a user to the "THANK YOU" page once the details of the same is submitted; However on submitting.. the user is not getting directed to the "THANK YOU PAGE". Can you please find out the mistake ? I would be really grateful.. THANK YOU SO MUCH!!  </p>

```<code><?php
include("company_profile/lib/data.config.php");
$btnsubmit  =isset($_POST['btnsubmit'])?$_POST['btnsubmit']:'';
if(isset($_POST['btnsubmit']))
{
$name = $_POST['name'];
$email = $_POST['email'];
$phone = $_POST['phone'];
$cource = $_POST['cource'];
$message = $_POST['message'];
$created_date = date('Y-m-d');
$time = date('H:i:s');
$q="Insert INTO enquiry_form SET name='$name',email='$email',
contact='$phone',message='$message',cource='$cource',
created_date='$created_date',etime='$time'";

    $r = mysqli_query($conn,$q);

   if($r)
    {
    //echo "Thankyou for Inquery";
    header("location:thanks.php");
    //echo "<script>alert('Message Send')</script>";

  }else
  {
    echo "there was a problem";
  }

  }

  ?>
</code>```

答:
use pdo again and filter your request

```<code><?php
include("company_profile/lib/data.config.php");
$btnsubmit  =isset($_POST['btnsubmit'])?$_POST['btnsubmit']:'';
if ($_SERVER['REQUEST_METHOD'] == 'POST'){
if(isset($_POST['btnsubmit']))
{
$name = $_POST['name']; // filter string  number encode ......
$email = $_POST['email']; // filter string number encode ......
$phone = $_POST['phone']; // filter string number encode ......
$cource = $_POST['cource']; // filter string number encode ......
$message = $_POST['message']; // filter string number encode ......
$created_date = date('Y-m-d'); // filter string number encode ......
// we are in 2017 use pdo
$pdo = $con->prepare("Insert INTO enquiry_form SET name= :name,email=:email,contact=:phone,message=:message,cource=:cource,created_date= now()");
$pdo->execute(array('name' => $name,'email' => $email, 'phone' => $phone, 'message' => $message, 'cource' => $cource ));
   if($pdo)
    {
    //echo "Thankyou for Inquery";
    header("location:thanks.php");
    //echo "<script>alert('Message Send')</script>";

  }else
  {
    echo "there was a problem";
  }

  }
}
 ?>`
</code>```

Body:
I have made a contact from... which is supposed to redirect a user to the "THANK YOU" page once the details of the same is submitted; However on submitting.. the user is not getting directed to the "THANK YOU PAGE". Can you please find out the mistake ? I would be really grateful.. THANK YOU SO MUCH!!

<?php
include("company_profile/lib/data.config.php");
$btnsubmit  =isset($_POST['btnsubmit'])?$_POST['btnsubmit']:'';
if(isset($_POST['btnsubmit']))
{
$name = $_POST['name'];
$email = $_POST['email'];
$phone = $_POST['phone'];
$cource = $_POST['cource'];
$message = $_POST['message'];
$created_date = date('Y-m-d');
$time = date('H:i:s');
$q="Insert INTO enquiry_form SET name='$name',email='$email',
contact='$phone',message='$message',cource='$cource',
created_date='$created_date',etime='$time'";

    $r = mysqli_query($conn,$q);

   if($r)
    {
    //echo "Thankyou for Inquery";
    header("location:thanks.php");
    //echo "";

  }else
  {
    echo "there was a problem";
  }

  }

  ?>

Body:
use pdo again and filter your request

<?php
include("company_profile/lib/data.config.php");
$btnsubmit  =isset($_POST['btnsubmit'])?$_POST['btnsubmit']:'';
if ($_SERVER['REQUEST_METHOD'] == 'POST'){
if(isset($_POST['btnsubmit']))
{
$name = $_POST['name']; // filter string  number encode ......
$email = $_POST['email']; // filter string number encode ......
$phone = $_POST['phone']; // filter string number encode ......
$cource = $_POST['cource']; // filter string number encode ......
$message = $_POST['message']; // filter string number encode ......
$created_date = date('Y-m-d'); // filter string number encode ......
// we are in 2017 use pdo
$pdo = $con->prepare("Insert INTO enquiry_form SET name= :name,email=:email,contact=:phone,message=:message,cource=:cource,created_date= now()");
$pdo->execute(array('name' => $name,'email' => $email, 'phone' => $phone, 'message' => $message, 'cource' => $cource ));
   if($pdo)
    {
    //echo "Thankyou for Inquery";
    header("location:thanks.php");
    //echo "<script>alert('Message Send')</script>";

  }else
  {
    echo "there was a problem";
  }

  }
}
 ?>`


问:
Master and Slaves failover from Slave snapshot
I plan to use MySQL setup with one master server and several slave
servers. I would perform regular consistent backup of the data EBS on one of the slave
servers (I will always stop database before and restart it when it is finished).

Slaves failover

I one of the slave fails, I will start new instance and moun EBS based on the latest slave snapshot as the new data disk. In this situation master is available all the time. So this is what I think I should do:

0) make sure server uses unique server_id
1) SLAVE STOP;

2) RESET SLAVE;

3) START SLAVE;

4) restart mysql?

Is that enough?

Master failover
For simplicity and consistency reasons I don't want to promote one of the slaves to master. I prefer to create new master from scratch. The problem is that the snapshot is from the slave and I want to use it as a master. This is what I think I should do after creating new instance with the disk based on the slave snapshot:

1) STOP SLAVE;

2) RESET MASTER;

3) restart mysql

4) associate elastic IP to the new master db (same IP was used by failed master), so the slaves will be able to connect again.

Is this procedure correct?
What should I do with the slaves now? Slaves can be ahead of the master, because master was restored from snapshot that can be several hours old. Is this problem? There is also possibility to recreate all the slaves from the same snapshot which was used to recover master. Then they would be on the same position as the master. But this could be complicated and impossible to proceed without downtime. Is there any better way how to do it?

Thank you very much in advance!

Notes: I don't mind lost transactions since the latest snapshot. I am using Mysql 5.1.41.

答:
Two method that I use to restore out-of-sync servers is:

re-import a dump from a 'good' server onto the 'bad' server.  In your case it would to import a dump from a good slave onto the bad master.

Run a program such a Navicat on the affected servers.  Navicat has a function that allows data synchronization between two tables (one way, two way, etc) so that any missing records are re-added.

In both methods you will need to stop the master and reset the master.  Reseting the slaves will also help.


问:
android font size of tabs
i ask this quest for a few time ago , but i get no solutions :(
my problem is, that i have an android app with a tab activity, where i have to set the font size of my tabs, but i don't know how.

in my activity i set my tabs programmatically:

```<code>    TabLayout tabLayout = (TabLayout) findViewById(R.id.tab_layout);
    tabLayout.addTab(tabLayout.newTab().setText("MY TAB 1"));
    tabLayout.addTab(tabLayout.newTab().setText("MY TAB 2"));
    tabLayout.addTab(tabLayout.newTab().setText("MY TAB 3"));
    tabLayout.setTabGravity(TabLayout.GRAVITY_FILL);
</code>```

Problem is, that the last 1 - 2 letters will be cut, so i have to set the font size smaller, but how?

i hope anyone can help me.

答:
```<code>#If you dont want to use style.xml and do by prgramatically the Use this in your xml layout. #
<android.support.design.widget.TabLayout
                android:id="@+id/tab_Layout_dashboard"
                android:layout_below="@id/ll_profile"
                android:layout_width="match_parent"
                android:layout_height="0dp"
                android:layout_weight="0.15"
                style="@style/Base.Widget.Design.TabLayout"
                android:theme="@style/ThemeOverlay.AppCompat.Dark.ActionBar"
                />

            <android.support.v4.view.ViewPager
                android:layout_below="@id/tab_Layout_dashboard"
                android:id="@+id/pager_tutor"
                android:layout_width="match_parent"
                android:layout_height="0dp"
                android:layout_weight="0.85"
                />

#In your activity or fragment use this method#

 private void changeTabsFont() {
        Typeface font = Typeface.createFromAsset(getActivity().getAssets(), "fonts/"+ Constants.FontStyle);
        ViewGroup vg = (ViewGroup) tab_layout.getChildAt(0);
        int tabsCount = vg.getChildCount();
        for (int j = 0; j < tabsCount; j++) {
            ViewGroup vgTab = (ViewGroup) vg.getChildAt(j);
            int tabChildsCount = vgTab.getChildCount();
            for (int i = 0; i < tabChildsCount; i++) {
                View tabViewChild = vgTab.getChildAt(i);
                if (tabViewChild instanceof TextView) {
                    ((TextView) tabViewChild).setTypeface(font);
                    ((TextView) tabViewChild).setTextSize(15);

                }
            }
        }
    }
</code>```

This code works for Tablayout change text color,type face(Font style) and also Text size. IF this works for you also then make correct so other user can easily solve his/her problem

Title: android font size of tabs

Body:
i ask this quest for a few time ago , but i get no solutions :(
my problem is, that i have an android app with a tab activity, where i have to set the font size of my tabs, but i don't know how.

in my activity i set my tabs programmatically:

    TabLayout tabLayout = (TabLayout) findViewById(R.id.tab_layout);
    tabLayout.addTab(tabLayout.newTab().setText("MY TAB 1"));
    tabLayout.addTab(tabLayout.newTab().setText("MY TAB 2"));
    tabLayout.addTab(tabLayout.newTab().setText("MY TAB 3"));
    tabLayout.setTabGravity(TabLayout.GRAVITY_FILL);

Problem is, that the last 1 - 2 letters will be cut, so i have to set the font size smaller, but how?

i hope anyone can help me.

Body:
#If you dont want to use style.xml and do by prgramatically the Use this in your xml layout. #
<android.support.design.widget.TabLayout
                android:id="@+id/tab_Layout_dashboard"
                android:layout_below="@id/ll_profile"
                android:layout_width="match_parent"
                android:layout_height="0dp"
                android:layout_weight="0.15"
                style="@style/Base.Widget.Design.TabLayout"
                android:theme="@style/ThemeOverlay.AppCompat.Dark.ActionBar"
                />

            <android.support.v4.view.ViewPager
                android:layout_below="@id/tab_Layout_dashboard"
                android:id="@+id/pager_tutor"
                android:layout_width="match_parent"
                android:layout_height="0dp"
                android:layout_weight="0.85"
                />

#In your activity or fragment use this method#

 private void changeTabsFont() {
        Typeface font = Typeface.createFromAsset(getActivity().getAssets(), "fonts/"+ Constants.FontStyle);
        ViewGroup vg = (ViewGroup) tab_layout.getChildAt(0);
        int tabsCount = vg.getChildCount();
        for (int j = 0; j < tabsCount; j++) {
            ViewGroup vgTab = (ViewGroup) vg.getChildAt(j);
            int tabChildsCount = vgTab.getChildCount();
            for (int i = 0; i < tabChildsCount; i++) {
                View tabViewChild = vgTab.getChildAt(i);
                if (tabViewChild instanceof TextView) {
                    ((TextView) tabViewChild).setTypeface(font);
                    ((TextView) tabViewChild).setTextSize(15);

                }
            }
        }
    }

This code works for Tablayout change text color,type face(Font style) and also Text size. IF this works for you also then make correct so other user can easily solve his/her problem


问:
Extract images using opencv and python or moviepy
I have a video (.mp4) that has ~8000 frames. I have a csv that tells me the time that I need to grab each frame at in the video, and the number of frames to grab.
number_of_frames in video = 8000
times is an array like [0.004, 0.005, ... 732s]
The last time in the data given is at 732s. Therefore the FPS = 8000 / 732 = ~10

I want to be able to extract the image frames from the video at those specific times. Then write those image paths to a .csv file.

I tried multiple approaches:
First approach(openCV):

```<code>with open('./data/driving.csv', 'w') as csvfile:
fieldnames = ['image_path', 'time', 'speed']
writer = csv.DictWriter(csvfile, fieldnames = fieldnames)
writer.writeheader()
vidcap = cv2.VideoCapture('./data/drive.mp4')
for idx, item in enumerate(ground_truth):
    # set video capture to specific time frame
    # multiply time by 1000 to convert to milliseconds
    vidcap.set(cv2.CAP_PROP_POS_MSEC, item[0] * 1000)
    # read in the image
    success, image = vidcap.read()
    if success:
        image_path = os.path.join('./data/IMG/', str(item[0]) +
     '.jpg')
        # save image to IMG folder
        cv2.imwrite(image_path, image)
        # write row to driving.csv
        writer.writerow({'image_path': image_path,
                 'time':item[0],
                 'speed':item[1],
                })
</code>```

This approach however, did not give me the total number of frames desired. It just gave me the number of frames that would correspond to a video at FPS = 25. I believe my FPS = 8000 / 732s = 10.928s.

I then tried using moviepy to capture each image in a similar style:

```<code>from moviepy.editor import VideoFileClip
clip1 = VideoFileClip('./data/drive.mp4')
with open('./data/driving.csv', 'w') as csvfile:
    fieldnames = ['image_path', 'time', 'speed']
    writer = csv.DictWriter(csvfile, fieldnames = fieldnames)
    writer.writeheader()

    # Path to raw image folder
    abs_path_to_IMG = os.path.join('./data/IMG/')
    for idx, item in enumerate(ground_truth):
      image_path = os.path.join('./data/IMG/', str(item[0]) + '.jpg')
      clip1.save_frame(image_path, t = item[0])
      # write row to driving.csv
      writer.writerow({'image_path': image_path,
             'time':item[0],
             'speed':item[1],
            })
</code>```

However this approach did not work either, for some reason I am capturing the last frame in the video hundreds of times.

答:
This code works OK to extract frames at different times:

```<code>import os
from moviepy.editor import *

def extract_frames(movie, times, imgdir):
    clip = VideoFileClip(movie)
    for t in times:
        imgpath = os.path.join(imgdir, '{}.png'.format(t))
        clip.save_frame(imgpath, t)

movie = 'movie.mp4'
imgdir = 'frames'
times = 0.1, 0.63, 0.947, 1.2, 3.8, 6.7

extract_frames(movie, times, imgdir)
</code>```

What's the content of your ground_truth variable?

Body:
I have a video (.mp4) that has ~8000 frames. I have a csv that tells me the time that I need to grab each frame at in the video, and the number of frames to grab.
number_of_frames in video = 8000
times is an array like [0.004, 0.005, ... 732s]
The last time in the data given is at 732s. Therefore the FPS = 8000 / 732 = ~10

I want to be able to extract the image frames from the video at those specific times. Then write those image paths to a .csv file.

I tried multiple approaches:
First approach(openCV):

with open('./data/driving.csv', 'w') as csvfile:
fieldnames = ['image_path', 'time', 'speed']
writer = csv.DictWriter(csvfile, fieldnames = fieldnames)
writer.writeheader()
vidcap = cv2.VideoCapture('./data/drive.mp4')
for idx, item in enumerate(ground_truth):
    # set video capture to specific time frame
    # multiply time by 1000 to convert to milliseconds
    vidcap.set(cv2.CAP_PROP_POS_MSEC, item[0] * 1000)
    # read in the image
    success, image = vidcap.read()
    if success:
        image_path = os.path.join('./data/IMG/', str(item[0]) +
     '.jpg')
        # save image to IMG folder
        cv2.imwrite(image_path, image)
        # write row to driving.csv
        writer.writerow({'image_path': image_path,
                 'time':item[0],
                 'speed':item[1],
                })

This approach however, did not give me the total number of frames desired. It just gave me the number of frames that would correspond to a video at FPS = 25. I believe my FPS = 8000 / 732s = 10.928s.

I then tried using moviepy to capture each image in a similar style:

from moviepy.editor import VideoFileClip
clip1 = VideoFileClip('./data/drive.mp4')
with open('./data/driving.csv', 'w') as csvfile:
    fieldnames = ['image_path', 'time', 'speed']
    writer = csv.DictWriter(csvfile, fieldnames = fieldnames)
    writer.writeheader()

    # Path to raw image folder
    abs_path_to_IMG = os.path.join('./data/IMG/')
    for idx, item in enumerate(ground_truth):
      image_path = os.path.join('./data/IMG/', str(item[0]) + '.jpg')
      clip1.save_frame(image_path, t = item[0])
      # write row to driving.csv
      writer.writerow({'image_path': image_path,
             'time':item[0],
             'speed':item[1],
            })

However this approach did not work either, for some reason I am capturing the last frame in the video hundreds of times.

Body:
This code works OK to extract frames at different times:

import os
from moviepy.editor import *

def extract_frames(movie, times, imgdir):
    clip = VideoFileClip(movie)
    for t in times:
        imgpath = os.path.join(imgdir, '{}.png'.format(t))
        clip.save_frame(imgpath, t)

movie = 'movie.mp4'
imgdir = 'frames'
times = 0.1, 0.63, 0.947, 1.2, 3.8, 6.7

extract_frames(movie, times, imgdir)

What's the content of your ground_truth variable?


问:
Disable Light probe icons

I've tried deactivating lights & light probe icons but this yellow lines and grey spheres keep appearing every time that i click an object.

I can hardly see the objects that im placing with that sphere overlaping them.

答: In the editor window there is a drop down menu named Gizmos in the top right corner. Click on it and unselect LightProbeGroup to hide it.

Title: Disable Light probe icons


问:
tkk checkbutton appears when loaded up with black box in it
I create a check button / box, with the following call

```<code>x=ttk.Checkbutton(tab1,state='disabled',command = lambda j=i,x=k: fCheckButton(j,x))
x.state(['selected'])
</code>```

The box appears fine and is selected, but it appears on load up, with a black box in it, which seems to have nothing to do with the state of it.

I have looked for reasons why, but can't actually find anyone with the same problem.

thanks

答:
I've had a similar issue on Windows 7.

After loading the app, one of my checkbuttons contained a filled square. But after clicking on it, it became a normal checkbutton:

In my case, it was because I had multiple checkbuttons sharing the same variable... After creating a separate Tk.IntVar() variable for each checkbutton, the problem disappeared.

```<code>import Tkinter as Tk
import ttk

root = Tk.Tk()

checkVar = Tk.IntVar()
x = ttk.Checkbutton(root, variable=checkVar, text="check 1")
x.pack()

checkVar2 = Tk.IntVar()
y = ttk.Checkbutton(root, variable=checkVar2, text="check 2")
y.pack()

root.mainloop()
</code>```

Body:
I create a check button / box, with the following call

x=ttk.Checkbutton(tab1,state='disabled',command = lambda j=i,x=k: fCheckButton(j,x))
x.state(['selected'])

The box appears fine and is selected, but it appears on load up, with a black box in it, which seems to have nothing to do with the state of it.

I have looked for reasons why, but can't actually find anyone with the same problem.

thanks

Body:
I've had a similar issue on Windows 7.

After loading the app, one of my checkbuttons contained a filled square. But after clicking on it, it became a normal checkbutton:

In my case, it was because I had multiple checkbuttons sharing the same variable... After creating a separate Tk.IntVar() variable for each checkbutton, the problem disappeared.

import Tkinter as Tk
import ttk

root = Tk.Tk()

checkVar = Tk.IntVar()
x = ttk.Checkbutton(root, variable=checkVar, text="check 1")
x.pack()

checkVar2 = Tk.IntVar()
y = ttk.Checkbutton(root, variable=checkVar2, text="check 2")
y.pack()

root.mainloop()


问:
Unable to parse a date string of format "dd/MM/yyyy HH:mm:ss" into JODA LocalDateTime
I am not able to parse a date string of format "dd/MM/yyyy HH:mm:ss" into JODA LocalDateTime.

I am getting below exception:
java.lang.IllegalArgumentException: Invalid format: "01/01/2017 00:30:00" is malformed at "/01/2017 00:30:00"

Please help me to fix this error.

See below my code:

```<code>public void calculateTOUValues(Date startDate, Date eDate, ArrayList<Double> csvDataPerChannel) {

    DateTimeFormatter format1 = DateTimeFormat.forPattern("dd/MM/yyyy HH:mm:ss");

    SimpleDateFormat format01 = new SimpleDateFormat("dd/MM/yyyy");
    String startDateString = format01.format(startDate) + " 00:30:00"; //concatenate 00:30:00
    String endDateString = format01.format(eDate) + " 00:00:00"; //concatenate 00:00:00

    LocalDateTime strDate = LocalDateTime.parse(startDateString); //exception encountered at this line of code
    LocalDateTime endDate = LocalDateTime.parse(endDateString);
}
</code>```

I am getting below exception on running this code:

Output: { SEVERE: null java.lang.IllegalArgumentException: Invalid
  format: "01/01/2017 00:30:00" is malformed at "/01/2017 00:30:00"     at
  org.joda.time.format.DateTimeFormatter.parseLocalDateTime(DateTimeFormatter.java:854)
    at org.joda.time.LocalDateTime.parse(LocalDateTime.java:168)    at
  org.joda.time.LocalDateTime.parse(LocalDateTime.java:157)     at
  module1.TOUCalculatorCore.calculateTOUValues(TOUCalculatorCore.java:135)
    at
  module1.LaunchTOUCalcTool.submitButtonActionPerformed(LaunchTOUCalcTool.java:807)
    at module1.LaunchTOUCalcTool.access$900(LaunchTOUCalcTool.java:32)
    at
  module1.LaunchTOUCalcTool$10.actionPerformed(LaunchTOUCalcTool.java:418)
    at
  javax.swing.AbstractButton.fireActionPerformed(AbstractButton.java:2022)
    at
  javax.swing.AbstractButton$Handler.actionPerformed(AbstractButton.java:2348)
    at
  javax.swing.DefaultButtonModel.fireActionPerformed(DefaultButtonModel.java:402)
    at
  javax.swing.DefaultButtonModel.setPressed(DefaultButtonModel.java:259)
    at
  javax.swing.plaf.basic.BasicButtonListener.mouseReleased(BasicButtonListener.java:252)
    at java.awt.Component.processMouseEvent(Component.java:6533)    at
  javax.swing.JComponent.processMouseEvent(JComponent.java:3324)    at
  java.awt.Component.processEvent(Component.java:6298)  at
  java.awt.Container.processEvent(Container.java:2236)  at
  java.awt.Component.dispatchEventImpl(Component.java:4889)     at
  java.awt.Container.dispatchEventImpl(Container.java:2294)     at
  java.awt.Component.dispatchEvent(Component.java:4711)     at
  java.awt.LightweightDispatcher.retargetMouseEvent(Container.java:4888)
    at
  java.awt.LightweightDispatcher.processMouseEvent(Container.java:4525)
    at java.awt.LightweightDispatcher.dispatchEvent(Container.java:4466)
    at java.awt.Container.dispatchEventImpl(Container.java:2280)    at
  java.awt.Window.dispatchEventImpl(Window.java:2746)   at
  java.awt.Component.dispatchEvent(Component.java:4711)     at
  java.awt.EventQueue.dispatchEventImpl(EventQueue.java:758)    at
  java.awt.EventQueue.access$500(EventQueue.java:97)    at
  java.awt.EventQueue$3.run(EventQueue.java:709)    at
  java.awt.EventQueue$3.run(EventQueue.java:703)    at
  java.security.AccessController.doPrivileged(Native Method)    at
  java.security.ProtectionDomain$JavaSecurityAccessImpl.doIntersectionPrivilege(ProtectionDomain.java:80)
    at
  java.security.ProtectionDomain$JavaSecurityAccessImpl.doIntersectionPrivilege(ProtectionDomain.java:90)
    at java.awt.EventQueue$4.run(EventQueue.java:731)   at
  java.awt.EventQueue$4.run(EventQueue.java:729)    at
  java.security.AccessController.doPrivileged(Native Method)    at
  java.security.ProtectionDomain$JavaSecurityAccessImpl.doIntersectionPrivilege(ProtectionDomain.java:80)
    at java.awt.EventQueue.dispatchEvent(EventQueue.java:728)   at
  java.awt.EventDispatchThread.pumpOneEventForFilters(EventDispatchThread.java:201)
    at
  java.awt.EventDispatchThread.pumpEventsForFilter(EventDispatchThread.java:116)
    at
  java.awt.EventDispatchThread.pumpEventsForHierarchy(EventDispatchThread.java:105)
    at
  java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:101)
    at
  java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:93)
    at java.awt.EventDispatchThread.run(EventDispatchThread.java:82) }

答:
Fixed the problem specifying the format. The below code worked, :)

```<code>    LocalDateTime strDate = LocalDateTime.parse(startDateString,
 DateTimeFormat.forPattern("dd/MM/yyyy HH:mm:ss"));
    LocalDateTime endDate = LocalDateTime.parse(endDateString,
 DateTimeFormat.forPattern("dd/MM/yyyy HH:mm:ss"));
</code>```

Thanks @thomas Klager

Body:
I am not able to parse a date string of format "dd/MM/yyyy HH:mm:ss" into JODA LocalDateTime.

I am getting below exception:
java.lang.IllegalArgumentException: Invalid format: "01/01/2017 00:30:00" is malformed at "/01/2017 00:30:00"

Please help me to fix this error.

See below my code:

public void calculateTOUValues(Date startDate, Date eDate, ArrayList<Double> csvDataPerChannel) {

    DateTimeFormatter format1 = DateTimeFormat.forPattern("dd/MM/yyyy HH:mm:ss");

    SimpleDateFormat format01 = new SimpleDateFormat("dd/MM/yyyy");
    String startDateString = format01.format(startDate) + " 00:30:00"; //concatenate 00:30:00
    String endDateString = format01.format(eDate) + " 00:00:00"; //concatenate 00:00:00

    LocalDateTime strDate = LocalDateTime.parse(startDateString); //exception encountered at this line of code
    LocalDateTime endDate = LocalDateTime.parse(endDateString);
}

I am getting below exception on running this code:

Output: { SEVERE: null java.lang.IllegalArgumentException: Invalid
  format: "01/01/2017 00:30:00" is malformed at "/01/2017 00:30:00"     at
  org.joda.time.format.DateTimeFormatter.parseLocalDateTime(DateTimeFormatter.java:854)
    at org.joda.time.LocalDateTime.parse(LocalDateTime.java:168)    at
  org.joda.time.LocalDateTime.parse(LocalDateTime.java:157)     at
  module1.TOUCalculatorCore.calculateTOUValues(TOUCalculatorCore.java:135)
    at
  module1.LaunchTOUCalcTool.submitButtonActionPerformed(LaunchTOUCalcTool.java:807)
    at module1.LaunchTOUCalcTool.access$900(LaunchTOUCalcTool.java:32)
    at
  module1.LaunchTOUCalcTool$10.actionPerformed(LaunchTOUCalcTool.java:418)
    at
  javax.swing.AbstractButton.fireActionPerformed(AbstractButton.java:2022)
    at
  javax.swing.AbstractButton$Handler.actionPerformed(AbstractButton.java:2348)
    at
  javax.swing.DefaultButtonModel.fireActionPerformed(DefaultButtonModel.java:402)
    at
  javax.swing.DefaultButtonModel.setPressed(DefaultButtonModel.java:259)
    at
  javax.swing.plaf.basic.BasicButtonListener.mouseReleased(BasicButtonListener.java:252)
    at java.awt.Component.processMouseEvent(Component.java:6533)    at
  javax.swing.JComponent.processMouseEvent(JComponent.java:3324)    at
  java.awt.Component.processEvent(Component.java:6298)  at
  java.awt.Container.processEvent(Container.java:2236)  at
  java.awt.Component.dispatchEventImpl(Component.java:4889)     at
  java.awt.Container.dispatchEventImpl(Container.java:2294)     at
  java.awt.Component.dispatchEvent(Component.java:4711)     at
  java.awt.LightweightDispatcher.retargetMouseEvent(Container.java:4888)
    at
  java.awt.LightweightDispatcher.processMouseEvent(Container.java:4525)
    at java.awt.LightweightDispatcher.dispatchEvent(Container.java:4466)
    at java.awt.Container.dispatchEventImpl(Container.java:2280)    at
  java.awt.Window.dispatchEventImpl(Window.java:2746)   at
  java.awt.Component.dispatchEvent(Component.java:4711)     at
  java.awt.EventQueue.dispatchEventImpl(EventQueue.java:758)    at
  java.awt.EventQueue.access$500(EventQueue.java:97)    at
  java.awt.EventQueue$3.run(EventQueue.java:709)    at
  java.awt.EventQueue$3.run(EventQueue.java:703)    at
  java.security.AccessController.doPrivileged(Native Method)    at
  java.security.ProtectionDomain$JavaSecurityAccessImpl.doIntersectionPrivilege(ProtectionDomain.java:80)
    at
  java.security.ProtectionDomain$JavaSecurityAccessImpl.doIntersectionPrivilege(ProtectionDomain.java:90)
    at java.awt.EventQueue$4.run(EventQueue.java:731)   at
  java.awt.EventQueue$4.run(EventQueue.java:729)    at
  java.security.AccessController.doPrivileged(Native Method)    at
  java.security.ProtectionDomain$JavaSecurityAccessImpl.doIntersectionPrivilege(ProtectionDomain.java:80)
    at java.awt.EventQueue.dispatchEvent(EventQueue.java:728)   at
  java.awt.EventDispatchThread.pumpOneEventForFilters(EventDispatchThread.java:201)
    at
  java.awt.EventDispatchThread.pumpEventsForFilter(EventDispatchThread.java:116)
    at
  java.awt.EventDispatchThread.pumpEventsForHierarchy(EventDispatchThread.java:105)
    at
  java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:101)
    at
  java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:93)
    at java.awt.EventDispatchThread.run(EventDispatchThread.java:82) }

Body:
Fixed the problem specifying the format. The below code worked, :)

    LocalDateTime strDate = LocalDateTime.parse(startDateString,
 DateTimeFormat.forPattern("dd/MM/yyyy HH:mm:ss"));
    LocalDateTime endDate = LocalDateTime.parse(endDateString,
 DateTimeFormat.forPattern("dd/MM/yyyy HH:mm:ss"));

Thanks @thomas Klager


问:
'LIKE' operator in sqlite query in FMDB
Please explain how I can write LIKE operator for code like this? I wrote code below but it seems not working on FMDB.

```<code>func getsearchStudentData(word:String) -> NSMutableArray {
sharedinstance.database!.open()
let resultSet: FMResultSet! = sharedinstance.database!.executeQuery("SELECT * FROM student_info WHERE name LIKE '%?' ",  withArgumentsInArray: [word])
let sarrStudentInfo : NSMutableArray = NSMutableArray()
if (resultSet != nil) {
    while resultSet.next() {
        let studentInfo : student_info = student_info()
        studentInfo.RollNo = resultSet.stringForColumn("RollNo")
        studentInfo.Name = resultSet.stringForColumn("Name")
        studentInfo.Marks = resultSet.stringForColumn("Mark")
        sarrStudentInfo.addObject(studentInfo)
    }
}
sharedinstance.database!.close()
return sarrStudentInfo           }
</code>```

答:
swift 3

try this

```<code>let query = "select \(field_ImageID) from \(imageTag_tableName) where \(field_ImageTag) LIKE ?;"
</code>```

...

```<code>let results = try database.executeQuery(query, values: ["%\(tag)%"])
</code>```

Title: 'LIKE' operator in sqlite query in FMDB

Body:
Please explain how I can write LIKE operator for code like this? I wrote code below but it seems not working on FMDB.

func getsearchStudentData(word:String) -> NSMutableArray {
sharedinstance.database!.open()
let resultSet: FMResultSet! = sharedinstance.database!.executeQuery("SELECT * FROM student_info WHERE name LIKE '%?' ",  withArgumentsInArray: [word])
let sarrStudentInfo : NSMutableArray = NSMutableArray()
if (resultSet != nil) {
    while resultSet.next() {
        let studentInfo : student_info = student_info()
        studentInfo.RollNo = resultSet.stringForColumn("RollNo")
        studentInfo.Name = resultSet.stringForColumn("Name")
        studentInfo.Marks = resultSet.stringForColumn("Mark")
        sarrStudentInfo.addObject(studentInfo)
    }
}
sharedinstance.database!.close()
return sarrStudentInfo           }

Body:
swift 3

try this

let query = "select \(field_ImageID) from \(imageTag_tableName) where \(field_ImageTag) LIKE ?;"

...

let results = try database.executeQuery(query, values: ["%\(tag)%"])


问:
Custom Url Rewriting in php
I am implementing a basic URL rewriting in a php application. Below is the approach I am following:

```<code>table 1: rewrite_table (fields as below)

id | original_url | custom_url
</code>```

This table I am using to store original URL and custom url.

I am checking in starting whether requested url is matched with any custom_url and if yes then I am calling controller and action which is being saved in original_url field

which is working fine. Now, point is if I change the custom url again then I want to keep the old url in a url log table and in case any user browse the webpage with that old url then (s)he will be redirect to new url with 301 redirect.

I have created a new table as

```<code>Table2: rewrite_table (fields as below)

log_original_url | current_url_id (this belongs to first table id filed)
</code>```

This table I am using to store old URL which is publically accessible to all before updating the url again which was already in 1st table.

I am confusing and unable to find any solution to implement the second approach.

Anyone can help me to find out a solution

Thanks

答:
Try this:

table 1: urls (internal_url is unique)

id | internal_url | current_alias_id

1  | user/index   | 3

2  | user/view    | 4

table 2: aliases (alias is unique)

id | internal_url_id | alias

1  | 1   | /my/custom/index/url/1

2  | 1   | /my/custom/index/url/2

3  | 1   | /my/custom/index/url/3

4  | 2   | /my/custom/view/url/1

The examples above illustrate a situation where each internal (in your terms "original") url can have one or more aliases. One of these aliases is always "current" or "canonical". When visited, it must be rewritten to the corresponding internal url, with no redirection happening. Internal URL always points to its canonical alias via the "current_alias_id" field. The other aliases, when visited, must be redirected to the "canonical" alias of the same internal URL.

In the examples, internal url "user/index" has 3 aliases, and its current (canonical) alias is #3, while the other 2 are "old".

The internal url "user/view" has only one alias #4, which is also canonical.

The required behavior, if I understand you properly, can be achieved with the following pseudo code:

```<code>record = SELECT a.*,
         u.current_alias_id, u.internal_url
         c.alias AS canonical_alias
         FROM `aliases` a
         INNER JOIN `urls` u ON a.original_url_id = u.id
         INNER JOIN `aliases` c ON u.current_alias_id = c.id
         WHERE a.alias = '$request_url';

// assume we found a record
if (record.id == record.current_alias_id)
    // rewrite to record.internal_url
else
    // redirect to record.canonical_alias
</code>```

Should you need to add a new alias, for example, to internal URL #2 (user/view) - just add it to the aliases table, where it will receive id = 5, and then UPDATE urls SET current_alias_id = 5 WHERE urls.id = 2

From now on, whoever visits the new alias, the request will be rewritten directly, and whoever visits the old alias #4, will be redirected to url #5.

Of course you should enforce that each "internal url" and each "alias" is unique, by setting a "unique" index on the corresponding columns.

Title: Custom Url Rewriting in php

Body:
I am implementing a basic URL rewriting in a php application. Below is the approach I am following:

table 1: rewrite_table (fields as below)

id | original_url | custom_url

This table I am using to store original URL and custom url.

I am checking in starting whether requested url is matched with any custom_url and if yes then I am calling controller and action which is being saved in original_url field

which is working fine. Now, point is if I change the custom url again then I want to keep the old url in a url log table and in case any user browse the webpage with that old url then (s)he will be redirect to new url with 301 redirect.

I have created a new table as

Table2: rewrite_table (fields as below)

log_original_url | current_url_id (this belongs to first table id filed)

This table I am using to store old URL which is publically accessible to all before updating the url again which was already in 1st table.

I am confusing and unable to find any solution to implement the second approach.

Anyone can help me to find out a solution

Thanks

Body:
Try this:

table 1: urls (internal_url is unique)

id | internal_url | current_alias_id

1  | user/index   | 3

2  | user/view    | 4

table 2: aliases (alias is unique)

id | internal_url_id | alias

1  | 1   | /my/custom/index/url/1

2  | 1   | /my/custom/index/url/2

3  | 1   | /my/custom/index/url/3

4  | 2   | /my/custom/view/url/1

The examples above illustrate a situation where each internal (in your terms "original") url can have one or more aliases. One of these aliases is always "current" or "canonical". When visited, it must be rewritten to the corresponding internal url, with no redirection happening. Internal URL always points to its canonical alias via the "current_alias_id" field. The other aliases, when visited, must be redirected to the "canonical" alias of the same internal URL.

In the examples, internal url "user/index" has 3 aliases, and its current (canonical) alias is #3, while the other 2 are "old".

The internal url "user/view" has only one alias #4, which is also canonical.

The required behavior, if I understand you properly, can be achieved with the following pseudo code:

record = SELECT a.*,
         u.current_alias_id, u.internal_url
         c.alias AS canonical_alias
         FROM `aliases` a
         INNER JOIN `urls` u ON a.original_url_id = u.id
         INNER JOIN `aliases` c ON u.current_alias_id = c.id
         WHERE a.alias = '$request_url';

// assume we found a record
if (record.id == record.current_alias_id)
    // rewrite to record.internal_url
else
    // redirect to record.canonical_alias

Should you need to add a new alias, for example, to internal URL #2 (user/view) - just add it to the aliases table, where it will receive id = 5, and then UPDATE urls SET current_alias_id = 5 WHERE urls.id = 2

From now on, whoever visits the new alias, the request will be rewritten directly, and whoever visits the old alias #4, will be redirected to url #5.

Of course you should enforce that each "internal url" and each "alias" is unique, by setting a "unique" index on the corresponding columns.


问:
Asking multiple permissions one at a time
The code just shows dialog box for the first permission and not for the other two permissions.How can I handle multiple requests in a much easier way other than this , in which the app prompts for each permission one at a time .

The code for requesting permission is as follows :

```<code>package com.example.hp.requesting_permissions;

import android.Manifest;
import android.content.pm.PackageManager;
import android.support.annotation.NonNull;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.widget.Toast;

public class MainActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        if (ContextCompat.checkSelfPermission(MainActivity.this,   Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED)     {
             if  (ActivityCompat.shouldShowRequestPermissionRationale(MainActivity.this,  Manifest.permission.ACCESS_FINE_LOCATION)) {
                ActivityCompat.requestPermissions(MainActivity.this, new String[]{Manifest.permission.ACCESS_FINE_LOCATION}, 1);
            } else {
                 ActivityCompat.requestPermissions(MainActivity.this, new String[]{Manifest.permission.ACCESS_FINE_LOCATION}, 1);
             }

         } else {
             Toast.makeText(MainActivity.this, "Denied",   Toast.LENGTH_SHORT).show();
         }

         if (ContextCompat.checkSelfPermission(MainActivity.this,   Manifest.permission.ACCESS_COARSE_LOCATION) !=   PackageManager.PERMISSION_GRANTED) {
            if   (ActivityCompat.shouldShowRequestPermissionRationale(MainActivity.this,   Manifest.permission.ACCESS_COARSE_LOCATION)) {
                ActivityCompat.requestPermissions(MainActivity.this, new   String[]{Manifest.permission.ACCESS_COARSE_LOCATION}, 2);
            } else {
                ActivityCompat.requestPermissions(MainActivity.this, new String[]{Manifest.permission.ACCESS_COARSE_LOCATION}, 2);
            }
        } else {
            Toast.makeText(MainActivity.this, "denied",   Toast.LENGTH_SHORT).show();
        }

        if (ContextCompat.checkSelfPermission(MainActivity.this,     Manifest.permission.INTERNET) != PackageManager.PERMISSION_GRANTED) {
            if   (ActivityCompat.shouldShowRequestPermissionRationale(MainActivity.this,      Manifest.permission.INTERNET)) {
                ActivityCompat.requestPermissions(MainActivity.this, new     String[]{Manifest.permission.INTERNET}, 3);
            } else {
                ActivityCompat.requestPermissions(MainActivity.this, new     String[]{Manifest.permission.INTERNET}, 3);
            }
        } else {
            Toast.makeText(MainActivity.this, "denied",  Toast.LENGTH_SHORT).show();
        }

    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[]     permissions, @NonNull int[] grantResults) {
        switch (requestCode) {
            case 1: {
                if (grantResults.length > 0 && grantResults[0] ==     PackageManager.PERMISSION_GRANTED) {
                    if (ContextCompat.checkSelfPermission(MainActivity.this,     Manifest.permission.ACCESS_FINE_LOCATION) == PackageManager.PERMISSION_GRANTED)     {
                        Toast.makeText(MainActivity.this, "Granted", Toast.LENGTH_SHORT).show();
                    } else {
                        Toast.makeText(MainActivity.this, "Denied",     Toast.LENGTH_SHORT).show();
                    }

                }
            }
            break;
            case 2: {
                 if (grantResults.length > 0 && grantResults[0] ==     PackageManager.PERMISSION_GRANTED) {
                    if (ContextCompat.checkSelfPermission(MainActivity.this,      Manifest.permission.ACCESS_COARSE_LOCATION) ==      PackageManager.PERMISSION_GRANTED) {
                        Toast.makeText(MainActivity.this, "Granted",     Toast.LENGTH_SHORT).show();
                    } else {
                        Toast.makeText(MainActivity.this, "Granted",      Toast.LENGTH_SHORT).show();
                    }
                }
            }
             break;
            case 3: {
                if (grantResults.length > 0 && grantResults[0] ==     PackageManager.PERMISSION_GRANTED) {
                    if (ContextCompat.checkSelfPermission(MainActivity.this,     Manifest.permission.INTERNET) == PackageManager.PERMISSION_GRANTED) {
                        Toast.makeText(MainActivity.this, "Granted",     Toast.LENGTH_SHORT).show();
                    } else {
                        Toast.makeText(MainActivity.this, "Denied",     Toast.LENGTH_SHORT).show();
                    }
                }
            }
            break;
        }
    }
}
</code>```

答:
You can use this piece of code by changing PERMISSIONS_ARR to your need or you can customise it to your need.

Add these code at top of class - global

```<code>private static final int REQUEST_PERMISSION = 1;

private static String[] PERMISSIONS_ARR = {
    Manifest.permission.READ_CONTACTS,
    Manifest.permission.WRITE_CONTACTS,
    Manifest.permission.READ_PHONE_STATE,
    Manifest.permission.READ_EXTERNAL_STORAGE,
    Manifest.permission.WRITE_EXTERNAL_STORAGE,
    Manifest.permission.PACKAGE_USAGE_STATS
};
</code>```

Call below function where you want to ask permission

```<code>public void askForPermission()
{

// Verify that all required contact permissions have been granted.
if (ActivityCompat.checkSelfPermission(this, Manifest.permission.READ_CONTACTS) != PackageManager.PERMISSION_GRANTED
        || ActivityCompat.checkSelfPermission(this, Manifest.permission.READ_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED
        || ActivityCompat.checkSelfPermission(this, Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED
        || ActivityCompat.checkSelfPermission(this, Manifest.permission.WRITE_CONTACTS) != PackageManager.PERMISSION_GRANTED
        || ActivityCompat.checkSelfPermission(this, Manifest.permission.READ_PHONE_STATE) != PackageManager.PERMISSION_GRANTED) {

    ActivityCompat.requestPermissions(this, PERMISSIONS_ARR, REQUEST_PERMISSION);

}
else
{
    // Permission already given do whatever you want...
}
}
</code>```

Add below code to track which permission is granted by user and which denied. Take decision according to that.

```<code>public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults)
{

if (requestCode == REQUEST_PERMISSION)
{
    // for each permission check if the user grantet/denied them
    // you may want to group the rationale in a single dialog,
    // this is just an example
    int count = 0;
    for (int i = 0, len = permissions.length; i < len; i++)
    {
        String permission = permissions[i];
        if (grantResults[i] == PackageManager.PERMISSION_GRANTED)
        {
            count++;
        }
        else
        {
            //Permission denied you can ask it for again.
        }
    }

    if (count == permissions.length)
    {
        // All permission granted
    }
    else
    {
        // Not all permission granted, controlled launch of application.
    }
}
}
</code>```

Body:
The code just shows dialog box for the first permission and not for the other two permissions.How can I handle multiple requests in a much easier way other than this , in which the app prompts for each permission one at a time .

The code for requesting permission is as follows :

package com.example.hp.requesting_permissions;

import android.Manifest;
import android.content.pm.PackageManager;
import android.support.annotation.NonNull;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.widget.Toast;

public class MainActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        if (ContextCompat.checkSelfPermission(MainActivity.this,   Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED)     {
             if  (ActivityCompat.shouldShowRequestPermissionRationale(MainActivity.this,  Manifest.permission.ACCESS_FINE_LOCATION)) {
                ActivityCompat.requestPermissions(MainActivity.this, new String[]{Manifest.permission.ACCESS_FINE_LOCATION}, 1);
            } else {
                 ActivityCompat.requestPermissions(MainActivity.this, new String[]{Manifest.permission.ACCESS_FINE_LOCATION}, 1);
             }

         } else {
             Toast.makeText(MainActivity.this, "Denied",   Toast.LENGTH_SHORT).show();
         }

         if (ContextCompat.checkSelfPermission(MainActivity.this,   Manifest.permission.ACCESS_COARSE_LOCATION) !=   PackageManager.PERMISSION_GRANTED) {
            if   (ActivityCompat.shouldShowRequestPermissionRationale(MainActivity.this,   Manifest.permission.ACCESS_COARSE_LOCATION)) {
                ActivityCompat.requestPermissions(MainActivity.this, new   String[]{Manifest.permission.ACCESS_COARSE_LOCATION}, 2);
            } else {
                ActivityCompat.requestPermissions(MainActivity.this, new String[]{Manifest.permission.ACCESS_COARSE_LOCATION}, 2);
            }
        } else {
            Toast.makeText(MainActivity.this, "denied",   Toast.LENGTH_SHORT).show();
        }

        if (ContextCompat.checkSelfPermission(MainActivity.this,     Manifest.permission.INTERNET) != PackageManager.PERMISSION_GRANTED) {
            if   (ActivityCompat.shouldShowRequestPermissionRationale(MainActivity.this,      Manifest.permission.INTERNET)) {
                ActivityCompat.requestPermissions(MainActivity.this, new     String[]{Manifest.permission.INTERNET}, 3);
            } else {
                ActivityCompat.requestPermissions(MainActivity.this, new     String[]{Manifest.permission.INTERNET}, 3);
            }
        } else {
            Toast.makeText(MainActivity.this, "denied",  Toast.LENGTH_SHORT).show();
        }

    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[]     permissions, @NonNull int[] grantResults) {
        switch (requestCode) {
            case 1: {
                if (grantResults.length > 0 && grantResults[0] ==     PackageManager.PERMISSION_GRANTED) {
                    if (ContextCompat.checkSelfPermission(MainActivity.this,     Manifest.permission.ACCESS_FINE_LOCATION) == PackageManager.PERMISSION_GRANTED)     {
                        Toast.makeText(MainActivity.this, "Granted", Toast.LENGTH_SHORT).show();
                    } else {
                        Toast.makeText(MainActivity.this, "Denied",     Toast.LENGTH_SHORT).show();
                    }

                }
            }
            break;
            case 2: {
                 if (grantResults.length > 0 && grantResults[0] ==     PackageManager.PERMISSION_GRANTED) {
                    if (ContextCompat.checkSelfPermission(MainActivity.this,      Manifest.permission.ACCESS_COARSE_LOCATION) ==      PackageManager.PERMISSION_GRANTED) {
                        Toast.makeText(MainActivity.this, "Granted",     Toast.LENGTH_SHORT).show();
                    } else {
                        Toast.makeText(MainActivity.this, "Granted",      Toast.LENGTH_SHORT).show();
                    }
                }
            }
             break;
            case 3: {
                if (grantResults.length > 0 && grantResults[0] ==     PackageManager.PERMISSION_GRANTED) {
                    if (ContextCompat.checkSelfPermission(MainActivity.this,     Manifest.permission.INTERNET) == PackageManager.PERMISSION_GRANTED) {
                        Toast.makeText(MainActivity.this, "Granted",     Toast.LENGTH_SHORT).show();
                    } else {
                        Toast.makeText(MainActivity.this, "Denied",     Toast.LENGTH_SHORT).show();
                    }
                }
            }
            break;
        }
    }
}

Body:
You can use this piece of code by changing PERMISSIONS_ARR to your need or you can customise it to your need.

Add these code at top of class - global

private static final int REQUEST_PERMISSION = 1;

private static String[] PERMISSIONS_ARR = {
    Manifest.permission.READ_CONTACTS,
    Manifest.permission.WRITE_CONTACTS,
    Manifest.permission.READ_PHONE_STATE,
    Manifest.permission.READ_EXTERNAL_STORAGE,
    Manifest.permission.WRITE_EXTERNAL_STORAGE,
    Manifest.permission.PACKAGE_USAGE_STATS
};

Call below function where you want to ask permission

public void askForPermission()
{

// Verify that all required contact permissions have been granted.
if (ActivityCompat.checkSelfPermission(this, Manifest.permission.READ_CONTACTS) != PackageManager.PERMISSION_GRANTED
        || ActivityCompat.checkSelfPermission(this, Manifest.permission.READ_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED
        || ActivityCompat.checkSelfPermission(this, Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED
        || ActivityCompat.checkSelfPermission(this, Manifest.permission.WRITE_CONTACTS) != PackageManager.PERMISSION_GRANTED
        || ActivityCompat.checkSelfPermission(this, Manifest.permission.READ_PHONE_STATE) != PackageManager.PERMISSION_GRANTED) {

    ActivityCompat.requestPermissions(this, PERMISSIONS_ARR, REQUEST_PERMISSION);

}
else
{
    // Permission already given do whatever you want...
}
}

Add below code to track which permission is granted by user and which denied. Take decision according to that.

public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults)
{

if (requestCode == REQUEST_PERMISSION)
{
    // for each permission check if the user grantet/denied them
    // you may want to group the rationale in a single dialog,
    // this is just an example
    int count = 0;
    for (int i = 0, len = permissions.length; i < len; i++)
    {
        String permission = permissions[i];
        if (grantResults[i] == PackageManager.PERMISSION_GRANTED)
        {
            count++;
        }
        else
        {
            //Permission denied you can ask it for again.
        }
    }

    if (count == permissions.length)
    {
        // All permission granted
    }
    else
    {
        // Not all permission granted, controlled launch of application.
    }
}
}


问:
Maven plugins to analyze javascript code quality
Javascript code can be tough to maintain.

I am looking for tools that will help me ensure a reasonable quality level.

So far I have found JsUNit, a very nice unit test framework for javascript. Tests can be run automatically from ant on any browser available.

I have not found yet some javascript equivalent of PMD, checkstyle, Findbug...

Do you know any static code analysis tool for javascript ?

答:
This project looks close:

http://dev.abiss.gr/mvn-jstools/index.html

It generates a report with JsLint.  It doesn't look like it hooks into the test phase of the build lifecycle, so I don't think it will reject a build if jslint finds issues (which is what I'd like to do on my projects).

LastEditorDisplayName: Hank Gay

OwnerDisplayName: jcooper


问:
Microsoft SQL Trigger: Will multiple join records pointing to the same record fail to update?
Background:

I have a set of products for each numbered week starting at 1.

I have a product "library" which is week zero holding the last saved product from any time period.

I have a trigger that fires upon update or insert which keeps the "library" item up to date from the inserted items.

Since there can be duplicate products in the same event using a "sequence" field, my join will create multiple records to update from, which target the same library record.

Some questions:

Will these multiples fail the update command?

Is there a better way to update the single library product?

Code:

```<code>-- PK is ID, Week #, and Sequence #
update p set p.name = i.name
from product p join inserted i on
     p.id = i.id and p.week = 0 and p.sequence = 1
</code>```

Note: "inserted" can have multiple events.  ID is like a UPC, Week is an identity, and Sequence is like an identity, but starts at 1 for each week.  You can have a sequence of 2 while not having a sequence of 1 because they can delete products.

Sample Data:

 ID  WeekSequence  Name

12345 1     3      Lego   inserted first

12345 2     2    Lego Toy inserted second

12345 2     3    Lego Toy inserted second

Result data:

 ID  WeekSequence  Name

12345 0     1    Lego Toy Was "Lego" now is "Lego Toy"

答:
According to this BOL entry:

Use caution when specifying the FROM
  clause to provide the criteria for the
  update operation. The results of an
  UPDATE statement are undefined if the
  statement includes a FROM clause that
  is not specified in such a way that
  only one value is available for each
  column occurrence that is updated,
  that is, if the UPDATE statement is
  not deterministic.

In other words, if an UPDATE statement uses a FROM clause that has multiple rows meeting the criteria to update a single row, it is unknown which row of new data will be used.  In your sample data, it is unknown whether the result was updated from the name in the row with Sequence=2 or Sequence=3.

So, if it doesn't matter which row is used for the update, what you're currently doing will work just fine.  If this is a problem however, you need to write your update's FROM and WHERE clauses so that only one row is returned for each item, possibly something like the following:

```<code>;with insert2 as (
  select id, week, sequence, name,
         row_number() over(partition by id order by week desc, sequence desc) as [descOrd]
  from inserted
)
update p
set p.name = i.name
from product p
  join insert2 i on p.id = i.id and p.week = 0 and p.sequence = 1
where i.descOrd=1
</code>```

Body:
Background:

I have a set of products for each numbered week starting at 1.

I have a product "library" which is week zero holding the last saved product from any time period.

I have a trigger that fires upon update or insert which keeps the "library" item up to date from the inserted items.

Since there can be duplicate products in the same event using a "sequence" field, my join will create multiple records to update from, which target the same library record.

Some questions:

Will these multiples fail the update command?

Is there a better way to update the single library product?

Code:

-- PK is ID, Week #, and Sequence #
update p set p.name = i.name
from product p join inserted i on
     p.id = i.id and p.week = 0 and p.sequence = 1

Note: "inserted" can have multiple events.  ID is like a UPC, Week is an identity, and Sequence is like an identity, but starts at 1 for each week.  You can have a sequence of 2 while not having a sequence of 1 because they can delete products.

Sample Data:

 ID  WeekSequence  Name

12345 1     3      Lego   inserted first

12345 2     2    Lego Toy inserted second

12345 2     3    Lego Toy inserted second

Result data:

 ID  WeekSequence  Name

12345 0     1    Lego Toy Was "Lego" now is "Lego Toy"

Body:
According to this BOL entry:

Use caution when specifying the FROM
  clause to provide the criteria for the
  update operation. The results of an
  UPDATE statement are undefined if the
  statement includes a FROM clause that
  is not specified in such a way that
  only one value is available for each
  column occurrence that is updated,
  that is, if the UPDATE statement is
  not deterministic.

In other words, if an UPDATE statement uses a FROM clause that has multiple rows meeting the criteria to update a single row, it is unknown which row of new data will be used.  In your sample data, it is unknown whether the result was updated from the name in the row with Sequence=2 or Sequence=3.

So, if it doesn't matter which row is used for the update, what you're currently doing will work just fine.  If this is a problem however, you need to write your update's FROM and WHERE clauses so that only one row is returned for each item, possibly something like the following:

;with insert2 as (
  select id, week, sequence, name,
         row_number() over(partition by id order by week desc, sequence desc) as [descOrd]
  from inserted
)
update p
set p.name = i.name
from product p
  join insert2 i on p.id = i.id and p.week = 0 and p.sequence = 1
where i.descOrd=1