问:
Mouse Down Event not firing (Bubbling events)
I am a novice to WPF. I started learning about RoutedEvents in WPF. I tried a sample and i met up with a problem

```<code>    <Grid Margin="5" Name="Grid" MouseDown="Window_MouseUp">
    <Grid.RowDefinitions>
        <RowDefinition Height="Auto"/>
        <RowDefinition Height="*"></RowDefinition>
        <RowDefinition Height="Auto"></RowDefinition>
        <RowDefinition Height="Auto"></RowDefinition>
    </Grid.RowDefinitions>
    <Label BorderBrush="Black" BorderThickness="1" Grid.Row="0" Margin="5"        Name="FancyLabel" MouseDown="Window_MouseUp" >
        <StackPanel Name="Stack" MouseDown="Window_MouseUp">
            <TextBlock Margin="3" Name="txtBlock1">
                Click Any Where
            </TextBlock>
            <TextBlock Margin="50" Name="txtBlock2" >
                Click me also
            </TextBlock>
        </StackPanel>
    </Label>
    <ListBox Grid.Row="1" Margin="5" Name="ListMessages"/>
    <Button Grid.Row="3" Margin="5" Name="cmd_Clear" MouseDown="Cmd_Clear_MouseDown"  >Clear</Button>
</Grid>
</code>```

The handler for the mouseDown event of the button is different from others int the tree hierarchy. The event is not firing..

But if i add in the .cs file the following code

```<code> Grid.AddHandler(UIElement.MouseDownEvent, new MouseButtonEventHandler(Window_MouseUp),true);
 Stack.AddHandler(UIElement.MouseDownEvent, new MouseButtonEventHandler(Window_MouseUp), true);
 FancyLabel.AddHandler(UIElement.MouseDownEvent, new MouseButtonEventHandler(Window_MouseUp), true);
 txtBlock1.AddHandler(UIElement.MouseDownEvent, new MouseButtonEventHandler(Window_MouseUp), true);
 txtBlock2.AddHandler(UIElement.MouseDownEvent, new MouseButtonEventHandler(Window_MouseUp), true);
 Img1.AddHandler(UIElement.MouseDownEvent, new MouseButtonEventHandler(Window_MouseUp), true);
 cmd_Clear.AddHandler(UIElement.MouseDownEvent, new MouseButtonEventHandler(Cmd_Clear_MouseDown), true);
</code>```

the Cmd_Clear_MouseDown event is fired and the event is bubbled up to the grid and the grid fires Window_MouseUp.

答:
Two points:

1) Is MouseDown="Window_MouseUp" everywhere intended?

2) Why not register to Click event with ClickMode="Press" instead of MouseDown. I don't think Button provides/raises MouseDown unless may be with a custom template.

Example:

```<code><Button Grid.Row="3"
        Margin="5"
        Name="cmd_Clear"
        ClickMode="Press"
        Click="Cmd_Clear_MouseDown">Clear</Button>
</code>```

Body:
I am a novice to WPF. I started learning about RoutedEvents in WPF. I tried a sample and i met up with a problem

    <Grid Margin="5" Name="Grid" MouseDown="Window_MouseUp">
    <Grid.RowDefinitions>
        <RowDefinition Height="Auto"/>
        <RowDefinition Height="*"></RowDefinition>
        <RowDefinition Height="Auto"></RowDefinition>
        <RowDefinition Height="Auto"></RowDefinition>
    </Grid.RowDefinitions>

        <StackPanel Name="Stack" MouseDown="Window_MouseUp">
            <TextBlock Margin="3" Name="txtBlock1">
                Click Any Where
            </TextBlock>
            <TextBlock Margin="50" Name="txtBlock2" >
                Click me also
            </TextBlock>
        </StackPanel>

    <ListBox Grid.Row="1" Margin="5" Name="ListMessages"/>
    <Button Grid.Row="3" Margin="5" Name="cmd_Clear" MouseDown="Cmd_Clear_MouseDown"  >Clear</Button>
</Grid>

The handler for the mouseDown event of the button is different from others int the tree hierarchy. The event is not firing..

But if i add in the .cs file the following code

 Grid.AddHandler(UIElement.MouseDownEvent, new MouseButtonEventHandler(Window_MouseUp),true);
 Stack.AddHandler(UIElement.MouseDownEvent, new MouseButtonEventHandler(Window_MouseUp), true);
 FancyLabel.AddHandler(UIElement.MouseDownEvent, new MouseButtonEventHandler(Window_MouseUp), true);
 txtBlock1.AddHandler(UIElement.MouseDownEvent, new MouseButtonEventHandler(Window_MouseUp), true);
 txtBlock2.AddHandler(UIElement.MouseDownEvent, new MouseButtonEventHandler(Window_MouseUp), true);
 Img1.AddHandler(UIElement.MouseDownEvent, new MouseButtonEventHandler(Window_MouseUp), true);
 cmd_Clear.AddHandler(UIElement.MouseDownEvent, new MouseButtonEventHandler(Cmd_Clear_MouseDown), true);

the Cmd_Clear_MouseDown event is fired and the event is bubbled up to the grid and the grid fires Window_MouseUp.

Body:
Two points:

1) Is MouseDown="Window_MouseUp" everywhere intended?

2) Why not register to Click event with ClickMode="Press" instead of MouseDown. I don't think Button provides/raises MouseDown unless may be with a custom template.

Example:

<Button Grid.Row="3"
        Margin="5"
        Name="cmd_Clear"
        ClickMode="Press"
        Click="Cmd_Clear_MouseDown">Clear</Button>


来源: stackexchange

问:
How to setup Selenium Server on RedHat linux?
I am trying to download the standlone jar file on my machine, but it is headless so I do not know what approach to take.

I have looked at similar questions which state

```<code>wget http://selenium.googlecode.com/files/selenium-server-standalone-2.28.0.jar
</code>```

to be a solution, but when I try this, it returns Network is unreachable.

How do I go about doing this?

答:
Disabled corporate proxy and then download worked.

Used another link too:
http://selenium-release.storage.googleapis.com/3.4/selenium-server-standalone-3.4.0.jar

ContentLicense: CC BY-SA 3.0

Body:
I am trying to download the standlone jar file on my machine, but it is headless so I do not know what approach to take.

I have looked at similar questions which state

wget http://selenium.googlecode.com/files/selenium-server-standalone-2.28.0.jar

to be a solution, but when I try this, it returns Network is unreachable.

How do I go about doing this?


问:
date format error-type mismatch
below is the code in which I am getting error at
If DOJ = " " Then. The error is "error 13, type mismatch"

I want to check if the cell is empty or not, if empty then change inner color to blue, but it is giving error as type mismatch.
Kindly help to resolve.

```<code>Sub BGVslaCheck()
fpath = Worksheets("Refrence").Range("C9").Value
fname = Worksheets("Refrence").Range("b9").Value & ".xlsx"
Dim Emp1 As Date
Dim DOJ As Date
Dim Cri As Date
Dim Edu As Date

'On Error Resume Next

Workbooks.Open (fpath & fname)
Worksheets("BGV").Select
Set wf = Application.WorksheetFunction
i = Range("a65536").End(xlUp).Row

For J = 11 To i

        DOJ = Worksheets("BGV").Range("c" & J).Value
        Cri = Worksheets("BGV").Range("g" & J).Value
        Edu = Worksheets("BGV").Range("i" & J).Value
        Emp1 = Worksheets("BGV").Range("K" & J).Value

        a = wf.NetworkDays(DOJ, Cri)
        b = wf.NetworkDays(DOJ, Edu)
        c = wf.NetworkDays(DOJ, Emp)
            Worksheets("BGV").Range("N" & J).Select
                If a > 14 Or b > 14 Or c > 14 Then
                    With Selection.Interior
                    .Color = VBA.RGB(250, 0, 0)
                    End With
                Else
                    With Selection.Interior
                    .Color = VBA.RGB(0, 250, 0)
                    End With
                End If

                'If DOJ = " " Or Cri = " " Or Edu = " " Then
                If DOJ = " " Then
                    With Selection.Interior
                    .Color = VBA.RGB(0, 0, 250)
                    End With
                End If
Next

Workbooks(fname).Close
</code>```

答:
DOJ is dimmed as a date, while your check is for a string. The below should work alternatively, you could keep it as a date and do if isempty(DOJ) then. </p>

```<code>Sub BGVslaCheck()
fpath = Worksheets("Refrence").Range("C9").Value
fname = Worksheets("Refrence").Range("b9").Value & ".xlsx"
Dim Emp1 As Date
Dim DOJ
Dim Cri As Date
Dim Edu As Date

'On Error Resume Next

Workbooks.Open (fpath & fname)
Worksheets("BGV").Select
Set wf = Application.WorksheetFunction
i = Range("a65536").End(xlUp).Row

For J = 11 To i

        DOJ = Worksheets("BGV").Range("c" & J).Value
        Cri = Worksheets("BGV").Range("g" & J).Value
        Edu = Worksheets("BGV").Range("i" & J).Value
        Emp1 = Worksheets("BGV").Range("K" & J).Value

        a = wf.NetworkDays(DOJ, Cri)
        b = wf.NetworkDays(DOJ, Edu)
        c = wf.NetworkDays(DOJ, Emp)
            Worksheets("BGV").Range("N" & J).Select
                If a > 14 Or b > 14 Or c > 14 Then
                    With Selection.Interior
                    .Color = VBA.RGB(250, 0, 0)
                    End With
                Else
                    With Selection.Interior
                    .Color = VBA.RGB(0, 250, 0)
                    End With
                End If
  'you could try: if isempty(DOJ) then
                'If DOJ = " " Or Cri = " " Or Edu = " " Then
                If DOJ = " " Then
                    With Selection.Interior
                    .Color = VBA.RGB(0, 0, 250)
                    End With
                End If
Next

Workbooks(fname).Close
</code>```

Title: date format error-type mismatch

Body:
below is the code in which I am getting error at
If DOJ = " " Then. The error is "error 13, type mismatch"

I want to check if the cell is empty or not, if empty then change inner color to blue, but it is giving error as type mismatch.
Kindly help to resolve.

Sub BGVslaCheck()
fpath = Worksheets("Refrence").Range("C9").Value
fname = Worksheets("Refrence").Range("b9").Value & ".xlsx"
Dim Emp1 As Date
Dim DOJ As Date
Dim Cri As Date
Dim Edu As Date

'On Error Resume Next

Workbooks.Open (fpath & fname)
Worksheets("BGV").Select
Set wf = Application.WorksheetFunction
i = Range("a65536").End(xlUp).Row

For J = 11 To i

        DOJ = Worksheets("BGV").Range("c" & J).Value
        Cri = Worksheets("BGV").Range("g" & J).Value
        Edu = Worksheets("BGV").Range("i" & J).Value
        Emp1 = Worksheets("BGV").Range("K" & J).Value

        a = wf.NetworkDays(DOJ, Cri)
        b = wf.NetworkDays(DOJ, Edu)
        c = wf.NetworkDays(DOJ, Emp)
            Worksheets("BGV").Range("N" & J).Select
                If a > 14 Or b > 14 Or c > 14 Then
                    With Selection.Interior
                    .Color = VBA.RGB(250, 0, 0)
                    End With
                Else
                    With Selection.Interior
                    .Color = VBA.RGB(0, 250, 0)
                    End With
                End If

                'If DOJ = " " Or Cri = " " Or Edu = " " Then
                If DOJ = " " Then
                    With Selection.Interior
                    .Color = VBA.RGB(0, 0, 250)
                    End With
                End If
Next

Workbooks(fname).Close

Body:
DOJ is dimmed as a date, while your check is for a string. The below should work alternatively, you could keep it as a date and do if isempty(DOJ) then.

Sub BGVslaCheck()
fpath = Worksheets("Refrence").Range("C9").Value
fname = Worksheets("Refrence").Range("b9").Value & ".xlsx"
Dim Emp1 As Date
Dim DOJ
Dim Cri As Date
Dim Edu As Date

'On Error Resume Next

Workbooks.Open (fpath & fname)
Worksheets("BGV").Select
Set wf = Application.WorksheetFunction
i = Range("a65536").End(xlUp).Row

For J = 11 To i

        DOJ = Worksheets("BGV").Range("c" & J).Value
        Cri = Worksheets("BGV").Range("g" & J).Value
        Edu = Worksheets("BGV").Range("i" & J).Value
        Emp1 = Worksheets("BGV").Range("K" & J).Value

        a = wf.NetworkDays(DOJ, Cri)
        b = wf.NetworkDays(DOJ, Edu)
        c = wf.NetworkDays(DOJ, Emp)
            Worksheets("BGV").Range("N" & J).Select
                If a > 14 Or b > 14 Or c > 14 Then
                    With Selection.Interior
                    .Color = VBA.RGB(250, 0, 0)
                    End With
                Else
                    With Selection.Interior
                    .Color = VBA.RGB(0, 250, 0)
                    End With
                End If
  'you could try: if isempty(DOJ) then
                'If DOJ = " " Or Cri = " " Or Edu = " " Then
                If DOJ = " " Then
                    With Selection.Interior
                    .Color = VBA.RGB(0, 0, 250)
                    End With
                End If
Next

Workbooks(fname).Close


问:
Why is toggleClass not working here?
I'm trying to add / remove a class on click here, but toggleClass is not working as I'm expecting it to. On the contrary, addClass works fine, but I need it to remove the class on the second click.

```<code>$('.label1').on('click', function() {
    var $checkItem = $(this).find('input[type=checkbox]');
    $(this).toggleClass('checked');
    $checkItem.prop("checked", !$checkItem.prop("checked"));
})

$('.label2').on('click', function() {
    var $checkItem = $(this).find('input[type=checkbox]');
    $(this).addClass('checked');
    $checkItem.prop("checked", !$checkItem.prop("checked"));
})
</code>```

Can you tell me what am I doing wrong?

See it in action here: Test jquery.

Thanks!

答:
You can avoid the problem and simplify your logic by instead hooking to the change event of the checkbox. This then lets you set the checked class on the parent label based on the state of the checked property.

Using change over click on the checkbox is also much better for meeting accessibility standards as it allows users who navigate using the keyboard to trigger the same effects in the UI. Try this:

$(':checkbox').on('change', function() {
  $(this).closest('label').toggleClass('checked', this.checked)
});```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.checked {
  border: 2px solid red;
}</code>```

<form>

      <input type="checkbox">
      Check me out

      <input type="checkbox">
      Check me out

</form>```

Title: Why is toggleClass not working here?

Body:
I'm trying to add / remove a class on click here, but toggleClass is not working as I'm expecting it to. On the contrary, addClass works fine, but I need it to remove the class on the second click.

$('.label1').on('click', function() {
    var $checkItem = $(this).find('input[type=checkbox]');
    $(this).toggleClass('checked');
    $checkItem.prop("checked", !$checkItem.prop("checked"));
})

$('.label2').on('click', function() {
    var $checkItem = $(this).find('input[type=checkbox]');
    $(this).addClass('checked');
    $checkItem.prop("checked", !$checkItem.prop("checked"));
})

Can you tell me what am I doing wrong?

See it in action here: Test jquery.

Thanks!

Body:
You can avoid the problem and simplify your logic by instead hooking to the change event of the checkbox. This then lets you set the checked class on the parent label based on the state of the checked property.

Using change over click on the checkbox is also much better for meeting accessibility standards as it allows users who navigate using the keyboard to trigger the same effects in the UI. Try this:

$(':checkbox').on('change', function() {
  $(this).closest('label').toggleClass('checked', this.checked)
});

.checked {
  border: 2px solid red;
}

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form>
  <div class="checkbox">
    <label class="label1">
      <input type="checkbox">
      Check me out
    </label>
  </div>
  <div class="checkbox">
    <label class="label2">
      <input type="checkbox">
      Check me out
    </label>
  </div>
</form>


问:
values not caltulating properly
I have created function to devide the values but the problem is that when place function parseInt and check it is avoiding numbers after (,) like if the value is 345,00.95 after using parseInt() it is becoming as 645 can any one help me out why is this happening </p>

```<code>  function liquid(val) {
    $(".overlay").show();
    $.ajax({
        url: "portfolio/getPortfolioInfo.php",
        dataType: "json",
        data: "portfolio_id=" + val,
        type: "post",
        error:function(){
            $(".overlay").hide();
        },
        success: function (data) {
            $(".overlay").hide();
            $("#liquidity").html(data.liquidity);
            var num_left = data.liquidity / parseFloat(<?php echo $company['price']; ?>);
            var rounded_value   = Math.round(num_left);
            $(".shares_left").html("<p>You can buy up to " + rounded_value + " </p>");
            console.log("liquidity" + parseInt(data.liquidity) + "rate" +parseFloat(<?php echo $company['price']; ?>));
        }
    });
}
</code>```

答:
considering the sample you provided

parseInt(345,00.95)

will output only the initial integer part that being

345

in your case

even if you had removed the initial ',' that is if your number was parseInt(34500.95) that will still give out just 34500 ignoring the decimal part

to achieve what you are looking for first remove all the ',' from your data

to do that use replace with a regex that matches all ',' within your data

(data.liquidity).replace(/,/g,'')

this will output

34500.95

and then apply  parseFloat to it

so your final code should be parseFloat((data.liquidity).replace(/,/g,''));

Title: values not caltulating properly

Body:
I have created function to devide the values but the problem is that when place function parseInt and check it is avoiding numbers after (,) like if the value is 345,00.95 after using parseInt() it is becoming as 645 can any one help me out why is this happening

  function liquid(val) {
    $(".overlay").show();
    $.ajax({
        url: "portfolio/getPortfolioInfo.php",
        dataType: "json",
        data: "portfolio_id=" + val,
        type: "post",
        error:function(){
            $(".overlay").hide();
        },
        success: function (data) {
            $(".overlay").hide();
            $("#liquidity").html(data.liquidity);
            var num_left = data.liquidity / parseFloat(<?php echo $company['price']; ?>);
            var rounded_value   = Math.round(num_left);
            $(".shares_left").html("
You can buy up to " + rounded_value + "
");
            console.log("liquidity" + parseInt(data.liquidity) + "rate" +parseFloat(<?php echo $company['price']; ?>));
        }
    });
}


问:
Php curl_multi_info_read curl_getinfo. Warning: supplied argument is not a valid cURL handle resource

Part of my code:

```<code>do{
    curl_multi_exec($mh, $running);
    $done = curl_multi_info_read($mh);
    $info = curl_getinfo($done['handle']);
 while($running > 0);
</code>```

This code results warning Warning: curl_getinfo(): supplied argument is not a valid cURL handle resource and i don't understand why. When i doing var_dump($done['handle']);     it's return resource(7) of type (curl). Please, help me find the error.

答:
For the proper use of curl_multi_exec, please use the following PHP Example:

```<code><?php
// create both cURL resources
$ch1 = curl_init();
$ch2 = curl_init();

// set URL and other appropriate options
curl_setopt($ch1, CURLOPT_URL, "http://lxr.php.net/");
curl_setopt($ch1, CURLOPT_HEADER, 0);
curl_setopt($ch2, CURLOPT_URL, "http://www.php.net/");
curl_setopt($ch2, CURLOPT_HEADER, 0);

//create the multiple cURL handle
$mh = curl_multi_init();

//add the two handles
curl_multi_add_handle($mh,$ch1);
curl_multi_add_handle($mh,$ch2);

$active = null;
//execute the handles
do {
    $mrc = curl_multi_exec($mh, $active);
} while ($mrc == CURLM_CALL_MULTI_PERFORM);

while ($active && $mrc == CURLM_OK) {
    if (curl_multi_select($mh) != -1) {
        do {
            $mrc = curl_multi_exec($mh, $active);
        } while ($mrc == CURLM_CALL_MULTI_PERFORM);
    }
}

//close the handles
curl_multi_remove_handle($mh, $ch1);
curl_multi_remove_handle($mh, $ch2);
curl_multi_close($mh);

?>
</code>```

Body:
Part of my code:

do{
    curl_multi_exec($mh, $running);
    $done = curl_multi_info_read($mh);
    $info = curl_getinfo($done['handle']);
 while($running > 0);

This code results warning Warning: curl_getinfo(): supplied argument is not a valid cURL handle resource and i don't understand why. When i doing var_dump($done['handle']);     it's return resource(7) of type (curl). Please, help me find the error.

Body:
For the proper use of curl_multi_exec, please use the following PHP Example:

<?php
// create both cURL resources
$ch1 = curl_init();
$ch2 = curl_init();

// set URL and other appropriate options
curl_setopt($ch1, CURLOPT_URL, "http://lxr.php.net/");
curl_setopt($ch1, CURLOPT_HEADER, 0);
curl_setopt($ch2, CURLOPT_URL, "http://www.php.net/");
curl_setopt($ch2, CURLOPT_HEADER, 0);

//create the multiple cURL handle
$mh = curl_multi_init();

//add the two handles
curl_multi_add_handle($mh,$ch1);
curl_multi_add_handle($mh,$ch2);

$active = null;
//execute the handles
do {
    $mrc = curl_multi_exec($mh, $active);
} while ($mrc == CURLM_CALL_MULTI_PERFORM);

while ($active && $mrc == CURLM_OK) {
    if (curl_multi_select($mh) != -1) {
        do {
            $mrc = curl_multi_exec($mh, $active);
        } while ($mrc == CURLM_CALL_MULTI_PERFORM);
    }
}

//close the handles
curl_multi_remove_handle($mh, $ch1);
curl_multi_remove_handle($mh, $ch2);
curl_multi_close($mh);

?>


问:
jquery .each , if statements do not work
I am trying to remove empty columns in sharepoint display forms. I am quite new to JQuery so bear with me!

I have:

```<code>$("td.ms-formbody").each(function (index) {
  if (index=6)
  {
    console.log("Mobile");
</code>```

So it loops through all the formbody tags and when it comes to the sixth one it should display "Mobile" to console.log but it is just logging 'Mobile' x the count of the formbody tags. So it seems that the IF is not working. Can anyone advise ?

答:
It look like you are new to passing functions as parameters as well.

Consider the following code:

```<code>$("td.ms-formbody").each(function(){});
</code>```

In this example I am parsing through all occurrences of the td.ms-formbody selector. I am passing a function through to each occurrence which can then operate on each instance of that selector. Currently I'm doing nothing.

Now consider the following:

```<code>$("td.ms-formbody").each(function(){
    $("td.ms-formbody").index($(this));
});
</code>```

This is one way of obtaining the index of each element. What JQuery is doing is getting all elements matching the selector and assigning them an arbitrary number based on the order in which they appear in the DOM. I can now operate on this information.

Using the correct conditional operator(==) and closing my if statement correctly, this will now log to the console if and when the each() function comes across a 6th element matching the selector.

```<code>$("td.ms-formbody").each(function(){
    if($("td.ms-formbody").index($(this)) == 6){
        console.log('Mobile');
    }
});
</code>```

Body:
I am trying to remove empty columns in sharepoint display forms. I am quite new to JQuery so bear with me!

I have:

$("td.ms-formbody").each(function (index) {
  if (index=6)
  {
    console.log("Mobile");

So it loops through all the formbody tags and when it comes to the sixth one it should display "Mobile" to console.log but it is just logging 'Mobile' x the count of the formbody tags. So it seems that the IF is not working. Can anyone advise ?

Body:
It look like you are new to passing functions as parameters as well.

Consider the following code:

$("td.ms-formbody").each(function(){});

In this example I am parsing through all occurrences of the td.ms-formbody selector. I am passing a function through to each occurrence which can then operate on each instance of that selector. Currently I'm doing nothing.

Now consider the following:

$("td.ms-formbody").each(function(){
    $("td.ms-formbody").index($(this));
});

This is one way of obtaining the index of each element. What JQuery is doing is getting all elements matching the selector and assigning them an arbitrary number based on the order in which they appear in the DOM. I can now operate on this information.

Using the correct conditional operator(==) and closing my if statement correctly, this will now log to the console if and when the each() function comes across a 6th element matching the selector.

$("td.ms-formbody").each(function(){
    if($("td.ms-formbody").index($(this)) == 6){
        console.log('Mobile');
    }
});


问:
Modal View Controllers appear behind Action Sheet
My modal view controllers are being shown behind my UIActionSheet, and my UIActionSheet is not getting dismissed. I am using:

```<code>[self presentModalViewController:composeTweetView animated:YES];
</code>```

To present my modal view controller.

My action sheet is being shown from the tabBar:

```<code>[actionSheet showFromTabBar:self.parentViewController.tabBarController.tabBar];
</code>```

This code worked on iOS 4.0.

```<code>if (buttonIndex == 0) {
        if (self.isLoggedIn) {
            [FlurryAPI logEvent:@"ST_REPLY_CLICKED"];
            composeTweetView.isDirectMessage = FALSE;
            [self presentModalViewController:composeTweetView animated:YES];
            [composeTweetView release];
        }
        else {
            LoginViewController* loginView = [[LoginViewController alloc] initWithNibName:@"LoginViewController" bundle:nil];
            loginView.delegate = self;
            loginView.isPostingComment = TRUE;
            self.isReply = TRUE;
            [self presentModalViewController:loginView animated:YES];
            [loginView release];
            [composeTweetView release];
        }
    }
</code>```

Summary:

I have a UIViewController that contains a UITabBar. I am presenting a UIActionSheet which has a few buttons that present a modal view controller. When the modal view controller is presented, the UIActionSheet should dismiss itself and the modal view should be on the top of the stack. The problem is, the UIActionSheet does not dismiss, and the modal view is loaded behind it. This problem did not occur up until iOS 4.2.1

Steps to Reproduce:

Create a TabBar project, setting
your Base SDK to iOS 4.2.1

Create a button or trigger to show a UIActionSheet

Allow one of the buttons in the UIActionSheet to present a modal view controller using the syntax: [actionSheet showFromTabBar:self.parentViewController.tabBarController.tabBar];

Expected Results:

```<code>1. The UIActionSheet should dismiss itself, and the modal view should appear in front
</code>```

Actual Results:

```<code>1. The UIActionSheet does not get dismissed and the modal view appears behind it.
</code>```

Regression:

```<code>This problem was not apparent prior to iOS 4.2.1
</code>```

Notes:
I have tried other ways of displaying the UIActionSheet all of which don't work as intended:

```<code>//[actionSheet showInView:self.parentViewController.tabBarController.tabBar];
//[actionSheet showInView:[self.view window]];
//[actionSheet showInView:self.parentViewController.tabBarController.view];
//[actionSheet showInView:[UIApplication sharedApplication].keyWindow];
</code>```

答:
I have also faced problems like this with iOS 4.2.
I think you should try with the following steps:

Create a separate method for the code you want to be executed on clicking the actionsheet button. suppose the method is -(void)presentModalView{}

2.Now in the - (void)actionSheet:(UIActionSheet *)actionSheet  clickedButtonAtIndex:(NSInteger)buttonIndex method,Call the presentModalView{} method for the clicked button index like this:

```<code>if(buttonIndex==0)
{
[self performSelector:@selector(presentModalView) withObject:nil afterDelay:0.3];
}
</code>```

3.You can also try by different delay time.

Hope it helps..

ContentLicense: CC BY-SA 2.5

Body:
My modal view controllers are being shown behind my UIActionSheet, and my UIActionSheet is not getting dismissed. I am using:

[self presentModalViewController:composeTweetView animated:YES];

To present my modal view controller.

My action sheet is being shown from the tabBar:

[actionSheet showFromTabBar:self.parentViewController.tabBarController.tabBar];

This code worked on iOS 4.0.

if (buttonIndex == 0) {
        if (self.isLoggedIn) {
            [FlurryAPI logEvent:@"ST_REPLY_CLICKED"];
            composeTweetView.isDirectMessage = FALSE;
            [self presentModalViewController:composeTweetView animated:YES];
            [composeTweetView release];
        }
        else {
            LoginViewController* loginView = [[LoginViewController alloc] initWithNibName:@"LoginViewController" bundle:nil];
            loginView.delegate = self;
            loginView.isPostingComment = TRUE;
            self.isReply = TRUE;
            [self presentModalViewController:loginView animated:YES];
            [loginView release];
            [composeTweetView release];
        }
    }

Summary:

I have a UIViewController that contains a UITabBar. I am presenting a UIActionSheet which has a few buttons that present a modal view controller. When the modal view controller is presented, the UIActionSheet should dismiss itself and the modal view should be on the top of the stack. The problem is, the UIActionSheet does not dismiss, and the modal view is loaded behind it. This problem did not occur up until iOS 4.2.1

Steps to Reproduce:

Create a TabBar project, setting
your Base SDK to iOS 4.2.1

Create a button or trigger to show a UIActionSheet

Allow one of the buttons in the UIActionSheet to present a modal view controller using the syntax: [actionSheet showFromTabBar:self.parentViewController.tabBarController.tabBar];

Expected Results:

1. The UIActionSheet should dismiss itself, and the modal view should appear in front

Actual Results:

1. The UIActionSheet does not get dismissed and the modal view appears behind it.

Regression:

This problem was not apparent prior to iOS 4.2.1

Notes:
I have tried other ways of displaying the UIActionSheet all of which don't work as intended:

//[actionSheet showInView:self.parentViewController.tabBarController.tabBar];
//[actionSheet showInView:[self.view window]];
//[actionSheet showInView:self.parentViewController.tabBarController.view];
//[actionSheet showInView:[UIApplication sharedApplication].keyWindow];

Body:
I have also faced problems like this with iOS 4.2.
I think you should try with the following steps:

Create a separate method for the code you want to be executed on clicking the actionsheet button. suppose the method is -(void)presentModalView{}

2.Now in the - (void)actionSheet:(UIActionSheet *)actionSheet  clickedButtonAtIndex:(NSInteger)buttonIndex method,Call the presentModalView{} method for the clicked button index like this:

if(buttonIndex==0)
{
[self performSelector:@selector(presentModalView) withObject:nil afterDelay:0.3];
}

3.You can also try by different delay time.

Hope it helps..


问:
How to get the url for admin page (including the key) in magento 2x custom module controller
I need the page url in Magento 2x including key in my custom module controller.
here something similar but this is for magento 1x. i need for magento 2x.

for magento 1x : Mage::helper('adminhtml')->getUrl('adminhtml/framexport/index') but i need similar for magento 2x.

答:
You can get admin url as follows:</p>

```<code>    public function __construct(\Magento\Backend\Helper\Data $HelperBackend
        ) {
         $this->HelperBackend = $HelperBackend;
        }

    /**
     *
     * @param \Magento\Framework\Event\Observer $observer
     * @return void
     */
    public function getAdminUrl()
    {
        echo $this->HelperBackend->getHomePageUrl();
    }
</code>```

Body:
You can get admin url as follows:

    public function __construct(\Magento\Backend\Helper\Data $HelperBackend
        ) {
         $this->HelperBackend = $HelperBackend;
        }

    /**
     *
     * @param \Magento\Framework\Event\Observer $observer
     * @return void
     */
    public function getAdminUrl()
    {
        echo $this->HelperBackend->getHomePageUrl();
    }


问:
How to send image in chat usig xmpp framework
Hi I am making an app based on the chatting I can send chat messages, but if i add image attachment to the chat message, its not working.here is my message code

```<code>if (![[messageStr stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]] length] && imgURL==nil) {
      return;
}
NSString *MyString;
NSDate *now = [NSDate date];
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setDateFormat:@"HH:mm,yyyy/MM/dd"];
MyString = [dateFormatter stringFromDate:now];
NSUserDefaults *defaults=[NSUserDefaults standardUserDefaults];
NSString *myJID=[defaults valueForKey:@"userNameJID"];

    if ([imgURL length]==0) {
       chatMessageToSendAndPutInDB=[messageStr mutableCopy];
       chatMessageToSendAndPutInDB=[[chatMessageToSendAndPutInDB stringByReplacingOccurrencesOfString:@"'" withString:@""] mutableCopy];
    }else
    {

       receivedDataString = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
          chatMessageToSendAndPutInDB=[receivedDataString mutableCopy];
        chatMessageToSendAndPutInDB=[[chatMessageToSendAndPutInDB stringByReplacingOccurrencesOfString:@"'" withString:@""] mutableCopy];

    }
    [DBObject open];
[DBObject insertInTable:@"chatTable" withUserId:myJID withFriendID:[[ASNGlobalClass shareManager] chatToUserJID] withMessage:chatMessageToSendAndPutInDB withTimeDate:MyString withLeftOrRight:0];

 NSXMLElement *body = [NSXMLElement elementWithName:@"body"];
[DBObject closeDatabase];
[self fetchDataFromDatabase];
   if([messageStr length] > 0 ) {

  [body setStringValue:messageStr];
   }else if ([imgURL length]>0){
             [body setStringValue:receivedDataString];
   }    NSXMLElement *message = [NSXMLElement elementWithName:@"message"];
[message addAttributeWithName:@"type" stringValue:@"chat"];

[message addAttributeWithName:@"to" stringValue:chatWithUser];
 NSXMLElement *chatStatus=[NSXMLElement elementWithName:@"composing" xmlns:UIApplicationStateActive];
[message addChild:chatStatus];
[message addChild:body];
[[[self appDelegate] xmppStream] sendElement:message];
</code>```

I am using xmpp framework and openfire server. and i don't know how to send images.please help me and i am using sqlite for storing and fetching
Thanks in advance.

答:
For sending a small image to friend you can use the below function, but for sending a large image/video/audio file, it is recommended to share large files  via streams "out of band" and use XMPP as signaling protocol - you should just send http:// or rtp:// link, and your buddy's client will download it, or start playing audio/video from given stream.

You can use XEP-0066: Out Of Band Data - simple extension, where you just attach URL to standard  element.

Sending Image

```<code>//Send Image to friend with message.
-(void)sendMessageWithImage:(NSString *)strText img:(UIImage *)SendImage {

    //Message string with image.
    NSString *messageStr = strText;

    NSXMLElement *body = [NSXMLElement elementWithName:@"body"];
    [body setStringValue:messageStr];

    NSXMLElement *message = [NSXMLElement elementWithName:@"message"];
    [message addAttributeWithName:@"type"stringValue:@"chat"];

    //set "to" string value to friend jid
    [message addAttributeWithName:@"to"stringValue:@"rohit@192.168.0.1"];
    [message addChild:body];

    NSData *dataPic =  UIImagePNGRepresentation(SendImage);

    NSXMLElement *photo = [NSXMLElement elementWithName:@"PHOTO"];
    NSXMLElement *binval = [NSXMLElement elementWithName:@"BINVAL"];
    [photo addChild:binval];

    //convert image to base64String
    NSString *base64String = [dataPic base64EncodedStringWithOptions:0];
    [binval setStringValue:base64String];
    [message addChild:photo];

    [[[self appDelegate] xmppStream] sendElement:message];

}
</code>```

at Receiver end

XMPPStream Delegate Methode.

```<code>- (void)xmppStream:(XMPPStream *)sender didReceiveMessage:(XMPPMessage *)message {

    [self MessageReceive:message];

}

#pragma mark - Receive New Message Methode.
-(void)MessageReceive:(XMPPMessage *)message
{
    //Get friend XMPPUserCoreDataStorageObject object
    XMPPUserCoreDataStorageObject *user = [xmppRosterStorage userForJID:[message from]
                                                             xmppStream:xmppStream
                                                   managedObjectContext:[self managedObjectContext_roster]];

    //Get Message if friend send with image.
    NSString *body = [[message elementForName:@"body"] stringValue];

    //Get Display name of friend.
    NSString *displayName = [user jidStr];

    //Check friend send image or only text message
    if ([message elementForName:@"PHOTO"]) {

        //Get Image from base64String
        NSString *photoHash = [[message elementForName:@"PHOTO"] stringValue];
        NSData* data = [photoHash dataUsingEncoding:NSUTF8StringEncoding];
        NSData *nsdataDecoded = [data initWithBase64EncodedData:data options:0];

        //Here you can get image.
        UIImage *image = [UIImage imageWithData:nsdataDecoded];

    } else {

        //Here you can get friend text message
        NSString *message = body;
    }
}
</code>```

Body:
Hi I am making an app based on the chatting I can send chat messages, but if i add image attachment to the chat message, its not working.here is my message code

if (![[messageStr stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]] length] && imgURL==nil) {
      return;
}
NSString *MyString;
NSDate *now = [NSDate date];
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setDateFormat:@"HH:mm,yyyy/MM/dd"];
MyString = [dateFormatter stringFromDate:now];
NSUserDefaults *defaults=[NSUserDefaults standardUserDefaults];
NSString *myJID=[defaults valueForKey:@"userNameJID"];

    if ([imgURL length]==0) {
       chatMessageToSendAndPutInDB=[messageStr mutableCopy];
       chatMessageToSendAndPutInDB=[[chatMessageToSendAndPutInDB stringByReplacingOccurrencesOfString:@"'" withString:@""] mutableCopy];
    }else
    {

       receivedDataString = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
          chatMessageToSendAndPutInDB=[receivedDataString mutableCopy];
        chatMessageToSendAndPutInDB=[[chatMessageToSendAndPutInDB stringByReplacingOccurrencesOfString:@"'" withString:@""] mutableCopy];

    }
    [DBObject open];
[DBObject insertInTable:@"chatTable" withUserId:myJID withFriendID:[[ASNGlobalClass shareManager] chatToUserJID] withMessage:chatMessageToSendAndPutInDB withTimeDate:MyString withLeftOrRight:0];

 NSXMLElement *body = [NSXMLElement elementWithName:@"body"];
[DBObject closeDatabase];
[self fetchDataFromDatabase];
   if([messageStr length] > 0 ) {

  [body setStringValue:messageStr];
   }else if ([imgURL length]>0){
             [body setStringValue:receivedDataString];
   }    NSXMLElement *message = [NSXMLElement elementWithName:@"message"];
[message addAttributeWithName:@"type" stringValue:@"chat"];

[message addAttributeWithName:@"to" stringValue:chatWithUser];
 NSXMLElement *chatStatus=[NSXMLElement elementWithName:@"composing" xmlns:UIApplicationStateActive];
[message addChild:chatStatus];
[message addChild:body];
[[[self appDelegate] xmppStream] sendElement:message];

I am using xmpp framework and openfire server. and i don't know how to send images.please help me and i am using sqlite for storing and fetching
Thanks in advance.

Body:
For sending a small image to friend you can use the below function, but for sending a large image/video/audio file, it is recommended to share large files  via streams "out of band" and use XMPP as signaling protocol - you should just send http:// or rtp:// link, and your buddy's client will download it, or start playing audio/video from given stream.

You can use XEP-0066: Out Of Band Data - simple extension, where you just attach URL to standard  element.

Sending Image

//Send Image to friend with message.
-(void)sendMessageWithImage:(NSString *)strText img:(UIImage *)SendImage {

    //Message string with image.
    NSString *messageStr = strText;

    NSXMLElement *body = [NSXMLElement elementWithName:@"body"];
    [body setStringValue:messageStr];

    NSXMLElement *message = [NSXMLElement elementWithName:@"message"];
    [message addAttributeWithName:@"type"stringValue:@"chat"];

    //set "to" string value to friend jid
    [message addAttributeWithName:@"to"stringValue:@"rohit@192.168.0.1"];
    [message addChild:body];

    NSData *dataPic =  UIImagePNGRepresentation(SendImage);

    NSXMLElement *photo = [NSXMLElement elementWithName:@"PHOTO"];
    NSXMLElement *binval = [NSXMLElement elementWithName:@"BINVAL"];
    [photo addChild:binval];

    //convert image to base64String
    NSString *base64String = [dataPic base64EncodedStringWithOptions:0];
    [binval setStringValue:base64String];
    [message addChild:photo];

    [[[self appDelegate] xmppStream] sendElement:message];

}

at Receiver end

XMPPStream Delegate Methode.

- (void)xmppStream:(XMPPStream *)sender didReceiveMessage:(XMPPMessage *)message {

    [self MessageReceive:message];

}

#pragma mark - Receive New Message Methode.
-(void)MessageReceive:(XMPPMessage *)message
{
    //Get friend XMPPUserCoreDataStorageObject object
    XMPPUserCoreDataStorageObject *user = [xmppRosterStorage userForJID:[message from]
                                                             xmppStream:xmppStream
                                                   managedObjectContext:[self managedObjectContext_roster]];

    //Get Message if friend send with image.
    NSString *body = [[message elementForName:@"body"] stringValue];

    //Get Display name of friend.
    NSString *displayName = [user jidStr];

    //Check friend send image or only text message
    if ([message elementForName:@"PHOTO"]) {

        //Get Image from base64String
        NSString *photoHash = [[message elementForName:@"PHOTO"] stringValue];
        NSData* data = [photoHash dataUsingEncoding:NSUTF8StringEncoding];
        NSData *nsdataDecoded = [data initWithBase64EncodedData:data options:0];

        //Here you can get image.
        UIImage *image = [UIImage imageWithData:nsdataDecoded];

    } else {

        //Here you can get friend text message
        NSString *message = body;
    }
}


问:
go concurrency all goroutines are asleep - deadlock
Sorry about the noob question but I'm having a hard time wrapping my head around the concurrency part of go. Basically this program below is a simplified version of a larger one I'm writing, thus I want to keep the structure similar to below.

Basically instead of waiting 4 seconds I want to run addCount(..) concurrent using the unbuffered channel and when all elements in the int_slice has been processed I want to do another operation on them. However this program ends with a "panic: close of closed channel" and if I remove the closing of the channel I'm getting the output I'm expecting but it panics with: "fatal error: all goroutines are asleep - deadlock"

How can I implement the concurrency part correctly in this scenario?

Thanks in advance!

```<code>package main

import (
    "fmt"
    "time"
)

func addCount(num int, counter chan<- int) {
    time.Sleep(time.Second * 2)
    counter <- num * 2
}

func main() {
    counter := make(chan int)
    int_slice := []int{2, 4}

    for _, item := range int_slice {
        go addCount(item, counter)
        close(counter)
    }

    for item := range counter {
        fmt.Println(item)
    }
}
</code>```

答:
Here are the issues I spotted in the code, and below a working version based on your implementation.

If a goroutine tries to write to an "unbuffered" channel, it will block until someone reads from it. Since you are not reading until they finish writing to the channel, you have a deadlock there.

Closing the channel while they are blocked breaks the deadlock, but gives an error since they now can't write to a closed channel.

Solution involves:

Creating a buffered channel so that they can write without blocking.

Using a sync.WaitGroup so that you wait for the goroutines to finish before closing the channel.

Reading from the channel at the end, when all is done.

See here, with comments:

```<code>    package main

    import (
        "fmt"
        "time"
        "sync"
    )

    func addCount(num int, counter chan<- int, wg *sync.WaitGroup) {
        // clear one from the sync group
        defer wg.Done()
        time.Sleep(time.Second * 2)
        counter <- num * 2
    }

    func main() {
        int_slice := []int{2, 4}
        // make the slice buffered using the slice size, so that they can write without blocking
        counter := make(chan int, len(int_slice))

        var wg sync.WaitGroup

        for _, item := range int_slice {
            // add one to the sync group, to mark we should wait for one more
            wg.Add(1)
            go addCount(item, counter, &wg)
        }

        // wait for all goroutines to end
        wg.Wait()

        // close the channel so that we not longer expect writes to it
        close(counter)

        // read remaining values in the channel
        for item := range counter {
            fmt.Println(item)
        }

    }
</code>```

ContentLicense: CC BY-SA 4.0

Body:
Sorry about the noob question but I'm having a hard time wrapping my head around the concurrency part of go. Basically this program below is a simplified version of a larger one I'm writing, thus I want to keep the structure similar to below.

Basically instead of waiting 4 seconds I want to run addCount(..) concurrent using the unbuffered channel and when all elements in the int_slice has been processed I want to do another operation on them. However this program ends with a "panic: close of closed channel" and if I remove the closing of the channel I'm getting the output I'm expecting but it panics with: "fatal error: all goroutines are asleep - deadlock"

How can I implement the concurrency part correctly in this scenario?

Thanks in advance!

package main

import (
    "fmt"
    "time"
)

func addCount(num int, counter chan<- int) {
    time.Sleep(time.Second * 2)
    counter <- num * 2
}

func main() {
    counter := make(chan int)
    int_slice := []int{2, 4}

    for _, item := range int_slice {
        go addCount(item, counter)
        close(counter)
    }

    for item := range counter {
        fmt.Println(item)
    }
}

Body:
Here are the issues I spotted in the code, and below a working version based on your implementation.

If a goroutine tries to write to an "unbuffered" channel, it will block until someone reads from it. Since you are not reading until they finish writing to the channel, you have a deadlock there.

Closing the channel while they are blocked breaks the deadlock, but gives an error since they now can't write to a closed channel.

Solution involves:

Creating a buffered channel so that they can write without blocking.

Using a sync.WaitGroup so that you wait for the goroutines to finish before closing the channel.

Reading from the channel at the end, when all is done.

See here, with comments:

    package main

    import (
        "fmt"
        "time"
        "sync"
    )

    func addCount(num int, counter chan<- int, wg *sync.WaitGroup) {
        // clear one from the sync group
        defer wg.Done()
        time.Sleep(time.Second * 2)
        counter <- num * 2
    }

    func main() {
        int_slice := []int{2, 4}
        // make the slice buffered using the slice size, so that they can write without blocking
        counter := make(chan int, len(int_slice))

        var wg sync.WaitGroup

        for _, item := range int_slice {
            // add one to the sync group, to mark we should wait for one more
            wg.Add(1)
            go addCount(item, counter, &wg)
        }

        // wait for all goroutines to end
        wg.Wait()

        // close the channel so that we not longer expect writes to it
        close(counter)

        // read remaining values in the channel
        for item := range counter {
            fmt.Println(item)
        }

    }


问:
ASP.NET UpdatePanel Error htmlfile: Unknown runtime error, updatePanelElement.innerHTML=rendering
I get this error when debugging my ASP.NET web application after I trigger an UpdatePanel:

htmlfile: Unknown runtime error

and "updatePanelElement.innerHTML=rendering" is highlighted in a ScriptResource.axd file.

答:
had the same error placed the update panel between the  tags by mistake instead of the nested  tags. That fix did it so i took it from this:

```<code><table>
<tr>
<asp:UpdatePanel runat="Server">
<ContentTemplate>
<td>

    //code here

</td>
</ContentTemplate>
</asp:UpdatePanel>
</td>
</table>
</code>```

to :

```<code><table>
<tr>
<td>
<asp:UpdatePanel runat="Server">
<ContentTemplate>

    //code here

</ContentTemplate>
</asp:UpdatePanel>
</td>
</code>```

OwnerDisplayName: Zack

Body:
had the same error placed the update panel between the  tags by mistake instead of the nested  tags. That fix did it so i took it from this:

<table>
<tr>
<asp:UpdatePanel runat="Server">
<ContentTemplate>
<td>

    //code here

</td>
</ContentTemplate>
</asp:UpdatePanel>
</td>
</table>

to :

<table>
<tr>
<td>
<asp:UpdatePanel runat="Server">
<ContentTemplate>

    //code here

</ContentTemplate>
</asp:UpdatePanel>
</td>


问:
How to select rows from db where the given date range falls?
The table structure:

```<code>ID   VersionID   ShiftType   Duration(Hr)   FromDate       ToDate
**********************************************************************
1    1           WORKING     12             20150702        20170528
2    1           WORKING     12             20150702        20170528
3    2           NOTWORKING  06             20170529        20170531
4    2           WORKING     06             20170529        20170531
5    2           NOTWORKING  06             20170529        20170531
6    2           WORKING     06             20170529        20170531
7    3           WORKING     08             20170601        0
8    3           NOTWORKING  08             20170601        0
9    3           WORKING     08             20170601        0
</code>```

Here you can see I have 3 version's(1,2,3) of shift(like day-shifts for 10 days and night-shifts for next 20 days etc).

The present followed shift will not have the end time(Row 7,8 and 9).

For example from 20150702 to 20170528 I followed version 1 which is of total 24 hours(1 day) working with two shifts and from 20170529 to 20170531 followed version 2 with four shifts two working and two nonworking of total 24 hours(1 day).

Now if user provides date range I should get the shift followed on that date range.

Provided date range: From 20170528 To 20170614.

Expected result: All Rows.

Working with below query:

```<code>SELECT * FROM SHIFTS
WHERE (FFROMDATE >= 20170528 AND FFROMDATE <= 20170614) OR (FTODATE >= 20170528 AND FTODATE <= 20170614)
</code>```

But doesn't work for: From 20170502 To 20170514.

Expected result: Rows 1,2(But none selected).

But doesn't work for: From 20170604 To 20170714.

Expected result: Rows 7,8,9(But none selected).

Thank you.

答:
This works for all three cases:

```<code>select *
  from shifts
  where fromdate <= range_end
    and range_start <= case when todate = 0 then 99991231 else todate end
</code>```

Test:

```<code>with shifts (id, fromdate, todate) as (
    select 1, 20150702, 20170528 from dual union all
    select 2, 20150702, 20170528 from dual union all
    select 3, 20170529, 20170531 from dual union all
    select 4, 20170529, 20170531 from dual union all
    select 5, 20170529, 20170531 from dual union all
    select 6, 20170529, 20170531 from dual union all
    select 7, 20170601,        0 from dual union all
    select 8, 20170601,        0 from dual union all
    select 9, 20170601,        0 from dual ),
ranges (range_id, range_start, range_end) as (
    select 1, 20170528, 20170614 from dual union all
    select 2, 20170502, 20170514 from dual union all
    select 3, 20170604, 20170714 from dual )
select *
  from shifts cross join ranges
  where fromdate <= range_end
    and range_start <= case when todate = 0 then 99991231 else todate end
  order by range_id, id
</code>```

Body:
The table structure:

ID   VersionID   ShiftType   Duration(Hr)   FromDate       ToDate
**********************************************************************
1    1           WORKING     12             20150702        20170528
2    1           WORKING     12             20150702        20170528
3    2           NOTWORKING  06             20170529        20170531
4    2           WORKING     06             20170529        20170531
5    2           NOTWORKING  06             20170529        20170531
6    2           WORKING     06             20170529        20170531
7    3           WORKING     08             20170601        0
8    3           NOTWORKING  08             20170601        0
9    3           WORKING     08             20170601        0

Here you can see I have 3 version's(1,2,3) of shift(like day-shifts for 10 days and night-shifts for next 20 days etc).

The present followed shift will not have the end time(Row 7,8 and 9).

For example from 20150702 to 20170528 I followed version 1 which is of total 24 hours(1 day) working with two shifts and from 20170529 to 20170531 followed version 2 with four shifts two working and two nonworking of total 24 hours(1 day).

Now if user provides date range I should get the shift followed on that date range.

Provided date range: From 20170528 To 20170614.

Expected result: All Rows.

Working with below query:

SELECT * FROM SHIFTS
WHERE (FFROMDATE >= 20170528 AND FFROMDATE <= 20170614) OR (FTODATE >= 20170528 AND FTODATE <= 20170614)

But doesn't work for: From 20170502 To 20170514.

Expected result: Rows 1,2(But none selected).

But doesn't work for: From 20170604 To 20170714.

Expected result: Rows 7,8,9(But none selected).

Thank you.

Body:
This works for all three cases:

select *
  from shifts
  where fromdate <= range_end
    and range_start <= case when todate = 0 then 99991231 else todate end

Test:

with shifts (id, fromdate, todate) as (
    select 1, 20150702, 20170528 from dual union all
    select 2, 20150702, 20170528 from dual union all
    select 3, 20170529, 20170531 from dual union all
    select 4, 20170529, 20170531 from dual union all
    select 5, 20170529, 20170531 from dual union all
    select 6, 20170529, 20170531 from dual union all
    select 7, 20170601,        0 from dual union all
    select 8, 20170601,        0 from dual union all
    select 9, 20170601,        0 from dual ),
ranges (range_id, range_start, range_end) as (
    select 1, 20170528, 20170614 from dual union all
    select 2, 20170502, 20170514 from dual union all
    select 3, 20170604, 20170714 from dual )
select *
  from shifts cross join ranges
  where fromdate <= range_end
    and range_start <= case when todate = 0 then 99991231 else todate end
  order by range_id, id


问:
std::vector<bool>::emplace in C++11
According to cppreference.com:

Notes

The specialization std::vector<bool> did not have emplace() member
  until C++14.

What does it mean? Can template specialization omit member? Does mean that member function is not present at all? Or is it just not specialized?

Following code seems to work on gcc 7.1.0:

```<code>#include <iostream>
#include <vector>
using namespace std;

int main()
{
    std::vector<bool> v;
    v.emplace_back(true);
    v.emplace_back(false);
    for (const auto &b : v) {
        std::cout << b << std::endl;
    }
}
</code>```

http://coliru.stacked-crooked.com/a/07c8c0fc6050968f

答:
A template specialization can be completely different from the generic template. So in theory, you cannot know whether the classes A<int> and A<bool> have any common members:

```<code>template <typename T>
class A
{
public:
    void foo()
    {}
};

template <>
class A<bool>
{
public:
    void bar()
    {}
};

int main()
{
    A<int> a;
    a.foo();

    A<bool> b;
    b.bar();

    b.foo();  // error: 'class A<bool>' has no member named 'foo'
}
</code>```

The class std::vector<bool> is a specialized template. Your quote from the standard says that the emplace() method was missing in that specialization until C++14.

In practice, concrete standard libraries such as libstdc++ may have provided the emplace() method for std::vector<bool> even before C++14, but it was not required in the standard.

Title: std::vector<bool>::emplace in C++11

Body:
According to cppreference.com:

Notes

The specialization std::vector<bool> did not have emplace() member
  until C++14.

What does it mean? Can template specialization omit member? Does mean that member function is not present at all? Or is it just not specialized?

Following code seems to work on gcc 7.1.0:

#include <iostream>
#include <vector>
using namespace std;

int main()
{
    std::vector<bool> v;
    v.emplace_back(true);
    v.emplace_back(false);
    for (const auto &b : v) {
        std::cout << b << std::endl;
    }
}

http://coliru.stacked-crooked.com/a/07c8c0fc6050968f

Body:
A template specialization can be completely different from the generic template. So in theory, you cannot know whether the classes A<int> and A<bool> have any common members:

template <typename T>
class A
{
public:
    void foo()
    {}
};

template <>
class A<bool>
{
public:
    void bar()
    {}
};

int main()
{
    A<int> a;
    a.foo();

    A<bool> b;
    b.bar();

    b.foo();  // error: 'class A<bool>' has no member named 'foo'
}

The class std::vector<bool> is a specialized template. Your quote from the standard says that the emplace() method was missing in that specialization until C++14.

In practice, concrete standard libraries such as libstdc++ may have provided the emplace() method for std::vector<bool> even before C++14, but it was not required in the standard.


问:
How to turn off dropout for testing in Tensorflow?
I am fairly new to Tensorflow and ML in general, so I hereby apologize for a (likely) trivial question.

I use the dropout technique to improve learning rates of my network, and it seems to work just fine. Then, I would like to test the network on some data to see if it works like this:

```<code>   def Ask(self, image):
        return self.session.run(self.model, feed_dict = {self.inputPh: image})
</code>```

Obviously, it yields different results each time as the dropout is still in place. One solution I can think of is to create two separate models - one for a training and the other one for an actual later use of the network, however, such a solution seems impractical to me.

What's the common approach to solving this problem?

答:
you should set the keep_prob in tensorflow dropout layer, that is the probability to keep the weight, I think you set that variable with values between 0.5 and 0.8.
When testing the network you must simply feed keep_prob with 1.

You should define something like that:

```<code>keep_prob = tf.placeholder(tf.float32, name='keep_prob')
drop = tf.contrib.rnn.DropoutWrapper(layer1, output_keep_prob=keep_prob)
</code>```

Then change the values in the session:

```<code>_ = sess.run(cost, feed_dict={'input':training_set, 'output':training_labels, 'keep_prob':0.8}) # During training
_ = sess.run(cost, feed_dict={'input':testing_set, 'output':testing_labels, 'keep_prob':1.}) # During testing
</code>```

Body:
I am fairly new to Tensorflow and ML in general, so I hereby apologize for a (likely) trivial question.

I use the dropout technique to improve learning rates of my network, and it seems to work just fine. Then, I would like to test the network on some data to see if it works like this:

   def Ask(self, image):
        return self.session.run(self.model, feed_dict = {self.inputPh: image})

Obviously, it yields different results each time as the dropout is still in place. One solution I can think of is to create two separate models - one for a training and the other one for an actual later use of the network, however, such a solution seems impractical to me.

What's the common approach to solving this problem?

Body:
you should set the keep_prob in tensorflow dropout layer, that is the probability to keep the weight, I think you set that variable with values between 0.5 and 0.8.
When testing the network you must simply feed keep_prob with 1.

You should define something like that:

keep_prob = tf.placeholder(tf.float32, name='keep_prob')
drop = tf.contrib.rnn.DropoutWrapper(layer1, output_keep_prob=keep_prob)

Then change the values in the session:

_ = sess.run(cost, feed_dict={'input':training_set, 'output':training_labels, 'keep_prob':0.8}) # During training
_ = sess.run(cost, feed_dict={'input':testing_set, 'output':testing_labels, 'keep_prob':1.}) # During testing


答:
The easiest way is to change the keep_prob parameter using a placeholder_with_default:

```<code>prob = tf.placeholder_with_default(1.0, shape=())
layer = tf.nn.dropout(layer, prob)
</code>```

in this way when you train you can set the parameter like this:

```<code>sess.run(train_step, feed_dict={prob: 0.5})
</code>```

and when you evaluate the default value of 1.0 is used.

Title: How to turn off dropout for testing in Tensorflow?

Body:
The easiest way is to change the keep_prob parameter using a placeholder_with_default:

prob = tf.placeholder_with_default(1.0, shape=())
layer = tf.nn.dropout(layer, prob)

in this way when you train you can set the parameter like this:

sess.run(train_step, feed_dict={prob: 0.5})

and when you evaluate the default value of 1.0 is used.


问:
When app in background firebase notification have notification with payload then remote message method call or not
I will try to getting data when app in background like this format

```<code>{
    "to" : "bk3RNwTe3H0:CI2k_HHwgIpoDKCIZvvDMExUdFQ3P1...",
    "notification" : {
      "body" : "great match!",
      "title" : "Portugal vs. Denmark",
      "icon" : "myicon"
    },
    "data" : {
     "Nick" : "Mario",
     "body" : "great match!",
     "Room" : "PortugalVSDenmark"
   }
}
</code>```

so data is delivered on onMessageReceived(RemoteMessage message) method or not i don't know can any one help me for this issue.

答:
For notifications to be clickable when your app is in the background, you need the click_action attribute in your notification payload.

Please check this section of the Firebase docs.

Also, when you define the click_action attribute, you will also need a corresponding <action> attribute in the <intent-filter> of the activity that you wish to launch.

This video explains it in quite a detailed manner.

Though, please note that you can not set the click__action attribute if you're sending notifications from the Firebase Console. You can only do so if you send a notification from your own Admin server or using Firebase Cloud Functions.

Lastly, in the activity that is launched, you can set additional Data using the data attribute ( also shown in the same doc that I linked above ). And when you launch your app by clicking on a notification, you can  obtain the notification data using getIntent(). Check out this answer for more details on how to do that.

For example, if your notification payload has the following structure,

```<code>payload = {
  notification: {
    title: `You ordered a new product`,
    click_action : 'HANDLE_NOTIFICATION',

  },
  data : {
        product_id : 'ABC98292',
        type : `Clothes`,
        product_name : 'Cotton spring shirt'
    }
};
</code>```

then, put the filter in the  tag of the activity that you want to open when the notification is clicked. An example is the following :-

```<code><intent-filter>
    <action android:name="HANDLE_NOTIFICATION" />
    <category android:name="android.intent.category.DEFAULT" />
    <category android:name="android.intent.category.BROWSABLE" />
</intent-filter>
</code>```

Then you can get the product_id from the notification using getIntent().getStringsExtra("product_id") and so on.

This way, you'll be opening the required activity, and can populate it with the relevant details obtained from your notification.

Body:
I will try to getting data when app in background like this format

{
    "to" : "bk3RNwTe3H0:CI2k_HHwgIpoDKCIZvvDMExUdFQ3P1...",
    "notification" : {
      "body" : "great match!",
      "title" : "Portugal vs. Denmark",
      "icon" : "myicon"
    },
    "data" : {
     "Nick" : "Mario",
     "body" : "great match!",
     "Room" : "PortugalVSDenmark"
   }
}

so data is delivered on onMessageReceived(RemoteMessage message) method or not i don't know can any one help me for this issue.

Body:
For notifications to be clickable when your app is in the background, you need the click_action attribute in your notification payload.

Please check this section of the Firebase docs.

Also, when you define the click_action attribute, you will also need a corresponding <action> attribute in the <intent-filter> of the activity that you wish to launch.

This video explains it in quite a detailed manner.

Though, please note that you can not set the click__action attribute if you're sending notifications from the Firebase Console. You can only do so if you send a notification from your own Admin server or using Firebase Cloud Functions.

Lastly, in the activity that is launched, you can set additional Data using the data attribute ( also shown in the same doc that I linked above ). And when you launch your app by clicking on a notification, you can  obtain the notification data using getIntent(). Check out this answer for more details on how to do that.

For example, if your notification payload has the following structure,

payload = {
  notification: {
    title: `You ordered a new product`,
    click_action : 'HANDLE_NOTIFICATION',

  },
  data : {
        product_id : 'ABC98292',
        type : `Clothes`,
        product_name : 'Cotton spring shirt'
    }
};

then, put the filter in the  tag of the activity that you want to open when the notification is clicked. An example is the following :-

<intent-filter>
    <action android:name="HANDLE_NOTIFICATION" />
    <category android:name="android.intent.category.DEFAULT" />
    <category android:name="android.intent.category.BROWSABLE" />
</intent-filter>

Then you can get the product_id from the notification using getIntent().getStringsExtra("product_id") and so on.

This way, you'll be opening the required activity, and can populate it with the relevant details obtained from your notification.


问:
Digging deeper into LSTM Keras
I am running a regression problem on sensor data having four columns using the LSTM framework. I have not yet used any regularization.

The code I used specified below;

```<code>import numpy as np
import matplotlib.pyplot as plt
import pandas as pd
import math
import keras
from keras.models import Sequential
from keras.layers import Dense, Dropout, Activation
from keras.layers import LSTM
from sklearn.preprocessing import MinMaxScaler
from sklearn.metrics import mean_squared_error
from keras import callbacks
from keras.layers import Flatten

# load the dataset
gbx_data = pd.read_csv('/home/prm/Downloads/aggregated_vibration.csv', usecols=[4,5,6,7])
dataset = gbx_data.values
dataset = dataset.astype('float32')

scaler = MinMaxScaler(feature_range=(0, 1))
dataset = scaler.fit_transform(dataset)

train_size = int(len(dataset) * 0.63)
test_size = len(dataset) - train_size
train, test = dataset[0:train_size,:], dataset[train_size:len(dataset),:]
print(len(train), len(test))

def create_dataset(dataset, look_back):
  dataX, dataY = [], []
  for i in range(len(dataset)-look_back-1):
    a = dataset[i:(i+look_back), :]
    dataX.append(a)
    dataY.append(dataset[i + look_back, :])
  return np.array(dataX), np.array(dataY)

look_back = 10
trainX, trainY = create_dataset(train, look_back)
testX, testY = create_dataset(test, look_back)

trainX = trainX.reshape(trainX.shape[0], look_back, trainX.shape[2])    # model input shape & model output shape will be same always #
testX = testX.reshape(testX.shape[0], look_back, testX.shape[2])

batch_size = 120

class LossHistory(keras.callbacks.Callback):
    def on_train_begin(self, logs={}):
        self.losses = []

    def on_epoch_end(self, epoch, logs={}):
        self.losses.append(logs.get('loss'))

model=Sequential()
model.add(LSTM(10, return_sequences=True, input_shape=(look_back, 4), activation='relu'))
model.add(Dropout(0.2))
model.add(LSTM(12, return_sequences=True, input_shape=(look_back, 4), activation='relu'))
model.add(Dropout(0.2))
model.add(Flatten())
model.add(Dense(4, activation='relu'))
model.compile(loss='mean_squared_error', optimizer='adam', metrics=['accuracy'])
history = LossHistory()
model.fit(trainX, trainY, epochs=10, batch_size=batch_size, callbacks=[history])
print(history.losses)
</code>```

I will like to know the specifications for the following questions;

For each epoch end, i am getting the loss for the LossHistory class. How   can I get the weights after each epoch? I know model.get_weights() gives me all the weights. But how can I get them after each epoch?

How can I optimally know which activation function I should use in LSTM & Dense layers so that my data performs 'best' & gives me good accuracy?

model.get_config() gives me 'stateful': False. If I execute a statefull LSTM, what change will actually occur & checking which values I can understand the change?

If return_sequences=False what change will occur?

How can I choose optimally the number of hidden nodes(neurons) for LSTM & Dense layer?

Running the above code, the loss history after 10 epochs are as follow,

```<code>[0.016399867401633194, 0.0029856997435597997, 0.0021351441705040426, 0.0016288172078515754, 0.0012535296516730061, 0.0010065438170736181, 0.00085688360991555948, 0.0007937529246583822, 0.00073356743746738303, 0.00069794598373472037]
</code>```

with accuracy 77%.

I am adding the table of several iterative approaches as well.

Sorry If I asked a lot. Please share your assistance if possible.

答:
Weights after each epoch:

For doing things after each epoch, you can use a Callback, especially the LambdaCallback, which allows a very flexible usage.

Define a lambda callback that will get weights after each epoch:

```<code>getWeightsCallback = LambdaCallback(on_epoch_end=getWeightsFunction)
</code>```

Where:

```<code>myWeights = []
def getWeightsFunction(epoch,logs):
    #adapt this code:
    myWeights.append(model.get_weights())
</code>```

Then add the callback to your fit method:

```<code>model.fit(....., callbacks=[getWeightsCallback])
</code>```

Activation functions

Unfortunately, I can't answer that, if there is an answer. But I do believe it's an intuitive thing, and it should be experimented until you find what is best for your specific task and model.

What I know, though, is about the last layer. This one is completely related to the final task.

A classification problem, with only one true class among many, benefits from using activation='softmax' and loss='categorical_crossentropy'

A classification problem with many true classes normally uses activation='sigmoid' and loss='binary_crossentropy'

Other problems should have better options too, depending on the application.

Stateful networks.

Recurrent networks have an "inner state", which is roughly the "memory" built from stepping through a sequence.

This state is unique for each sequence. Each sequence builds a state.

In non-stateful networks, the state is reset for every sequence

In stateful networks, the state is not automatically reset.

The idea of not resetting the states is to be able to divide each sequence in batches. If your sequences are too long (causing RAM or performance issues), you divide them in parts, and the model will understand that your batches are not "new sequences", but "sequels of the previous sequences".

The noticeable changes are the need of defining extra parameters such as batch size and passing the data correctly in sequence.

Keras documentation

An indirectly related question

Return sequences

Since recurrent networks work in time steps, every time step has a result.

You may choose to output all these results, ending up with a sequence (same number of time steps as the input). Or you may choose to get only the final result, discarding the time steps:

Return sequences=True: outputs (batch size, time steps, memory cells)

Return sequences=False: outputs (batch size, memory cells)

Same documentation as before

Ideal number of cells

Sorry, that is definitely an open question. It's totally dependent on what you want to do, the size of your data, the architecture of your model.

There is really no ready answer. Creating a perfect architecture for a certain application is exactly what everyone is seeking around the world.

You can make experiments or try to find papers that work with the same kind of thing you are working to see what are the best practices "so far".

Some related problems:

Overfitting: your model is too strong, or you have too little data. Your training accuracy gets great, but your validation accuracy doesn't evolve. Roughly, the model is memorizing the training data because it's just too good

Underfitting: your model is too weak, it simply can't solve the task

Title: Digging deeper into LSTM Keras

Body:
I am running a regression problem on sensor data having four columns using the LSTM framework. I have not yet used any regularization.

The code I used specified below;

import numpy as np
import matplotlib.pyplot as plt
import pandas as pd
import math
import keras
from keras.models import Sequential
from keras.layers import Dense, Dropout, Activation
from keras.layers import LSTM
from sklearn.preprocessing import MinMaxScaler
from sklearn.metrics import mean_squared_error
from keras import callbacks
from keras.layers import Flatten

# load the dataset
gbx_data = pd.read_csv('/home/prm/Downloads/aggregated_vibration.csv', usecols=[4,5,6,7])
dataset = gbx_data.values
dataset = dataset.astype('float32')

scaler = MinMaxScaler(feature_range=(0, 1))
dataset = scaler.fit_transform(dataset)

train_size = int(len(dataset) * 0.63)
test_size = len(dataset) - train_size
train, test = dataset[0:train_size,:], dataset[train_size:len(dataset),:]
print(len(train), len(test))

def create_dataset(dataset, look_back):
  dataX, dataY = [], []
  for i in range(len(dataset)-look_back-1):
    a = dataset[i:(i+look_back), :]
    dataX.append(a)
    dataY.append(dataset[i + look_back, :])
  return np.array(dataX), np.array(dataY)

look_back = 10
trainX, trainY = create_dataset(train, look_back)
testX, testY = create_dataset(test, look_back)

trainX = trainX.reshape(trainX.shape[0], look_back, trainX.shape[2])    # model input shape & model output shape will be same always #
testX = testX.reshape(testX.shape[0], look_back, testX.shape[2])

batch_size = 120

class LossHistory(keras.callbacks.Callback):
    def on_train_begin(self, logs={}):
        self.losses = []

    def on_epoch_end(self, epoch, logs={}):
        self.losses.append(logs.get('loss'))

model=Sequential()
model.add(LSTM(10, return_sequences=True, input_shape=(look_back, 4), activation='relu'))
model.add(Dropout(0.2))
model.add(LSTM(12, return_sequences=True, input_shape=(look_back, 4), activation='relu'))
model.add(Dropout(0.2))
model.add(Flatten())
model.add(Dense(4, activation='relu'))
model.compile(loss='mean_squared_error', optimizer='adam', metrics=['accuracy'])
history = LossHistory()
model.fit(trainX, trainY, epochs=10, batch_size=batch_size, callbacks=[history])
print(history.losses)

I will like to know the specifications for the following questions;

For each epoch end, i am getting the loss for the LossHistory class. How   can I get the weights after each epoch? I know model.get_weights() gives me all the weights. But how can I get them after each epoch?

How can I optimally know which activation function I should use in LSTM & Dense layers so that my data performs 'best' & gives me good accuracy?

model.get_config() gives me 'stateful': False. If I execute a statefull LSTM, what change will actually occur & checking which values I can understand the change?

If return_sequences=False what change will occur?

How can I choose optimally the number of hidden nodes(neurons) for LSTM & Dense layer?

Running the above code, the loss history after 10 epochs are as follow,

[0.016399867401633194, 0.0029856997435597997, 0.0021351441705040426, 0.0016288172078515754, 0.0012535296516730061, 0.0010065438170736181, 0.00085688360991555948, 0.0007937529246583822, 0.00073356743746738303, 0.00069794598373472037]

with accuracy 77%.

I am adding the table of several iterative approaches as well.

Sorry If I asked a lot. Please share your assistance if possible.

Body:
Weights after each epoch:

For doing things after each epoch, you can use a Callback, especially the LambdaCallback, which allows a very flexible usage.

Define a lambda callback that will get weights after each epoch:

getWeightsCallback = LambdaCallback(on_epoch_end=getWeightsFunction)

Where:

myWeights = []
def getWeightsFunction(epoch,logs):
    #adapt this code:
    myWeights.append(model.get_weights())

Then add the callback to your fit method:

model.fit(....., callbacks=[getWeightsCallback])

Activation functions

Unfortunately, I can't answer that, if there is an answer. But I do believe it's an intuitive thing, and it should be experimented until you find what is best for your specific task and model.

What I know, though, is about the last layer. This one is completely related to the final task.

A classification problem, with only one true class among many, benefits from using activation='softmax' and loss='categorical_crossentropy'

A classification problem with many true classes normally uses activation='sigmoid' and loss='binary_crossentropy'

Other problems should have better options too, depending on the application.

Stateful networks.

Recurrent networks have an "inner state", which is roughly the "memory" built from stepping through a sequence.

This state is unique for each sequence. Each sequence builds a state.

In non-stateful networks, the state is reset for every sequence

In stateful networks, the state is not automatically reset.

The idea of not resetting the states is to be able to divide each sequence in batches. If your sequences are too long (causing RAM or performance issues), you divide them in parts, and the model will understand that your batches are not "new sequences", but "sequels of the previous sequences".

The noticeable changes are the need of defining extra parameters such as batch size and passing the data correctly in sequence.

Keras documentation

An indirectly related question

Return sequences

Since recurrent networks work in time steps, every time step has a result.

You may choose to output all these results, ending up with a sequence (same number of time steps as the input). Or you may choose to get only the final result, discarding the time steps:

Return sequences=True: outputs (batch size, time steps, memory cells)

Return sequences=False: outputs (batch size, memory cells)

Same documentation as before

Ideal number of cells

Sorry, that is definitely an open question. It's totally dependent on what you want to do, the size of your data, the architecture of your model.

There is really no ready answer. Creating a perfect architecture for a certain application is exactly what everyone is seeking around the world.

You can make experiments or try to find papers that work with the same kind of thing you are working to see what are the best practices "so far".

Some related problems:

Overfitting: your model is too strong, or you have too little data. Your training accuracy gets great, but your validation accuracy doesn't evolve. Roughly, the model is memorizing the training data because it's just too good

Underfitting: your model is too weak, it simply can't solve the task


问:
java compare multiple values and find best match
I need to find best matched employee salary in the DB records as:

```<code>Name:   City:     State:

A       (null)    (null)

A       (null)    DEL

(null)  (null)    (null)

A        SAKET    DEL
</code>```

Match order should be:

1. NAME = name, STATE = state, CITY = city

2. NAME = name, STATE = state , CITY = NULL

3. NAME = name, STATE = NULL, CITY = NULL

4. NAME = NULL, STATE = NULL, CITY = NULL

Means if in a row where all attributes matches – it should be selected, if we do not have that kind of data we should go to next best option like select state and city as NULL, etc.

My code as below, is giving me correct results but I need a more efficient way.

```<code>    private static BigDecimal getsalaryForBestMatch(ResultSet results, EmployeeRq request) throws Exception{
    BigDecimal salary = null;
    BigDecimal salaryWithState = null;
    BigDecimal salaryWithName = null;
    BigDecimal salaryWithNoMatch = null;
     while (results.next()) {

        String billerName = results.getString("EMP_NAME") != null ? results.getString("EMP_NAME").trim() : null;
        String city = results.getString("CITY") != null ? results.getString("CITY").trim() : null;
        String state = results.getString("STATE") != null ? results.getString("STATE").trim() : null;

        BigDecimal salaryRslt = null;

        if(results.getString("SALARY") != null){
            salaryRslt = BigDecimal.valueOf(results.getDouble("SALARY"));
        }
        if(billerName != null && !billerName.equals("") && billerName.equals(request.getBillPaymentsalaryCalculateInfo().getBillerName())){
            if(city != null && !city.equals("") && city.equals(request.getMsgRqHdr().getCity()) &&
                    state != null && !state.equals("") && state.equalsIgnoreCase(request.getMsgRqHdr().getstate())){
                salary = salaryRslt;
                break;
            } else if((city == null || city.equals("")) && state != null && !state.equals("") &&
                    state.equalsIgnoreCase(request.getMsgRqHdr().getState())){
                salaryWithState = salaryRslt;
            } else if((city == null || city.equals("")) && (state == null || state.equals(""))){
                salaryWithName = salaryRslt;
            }
        } else if((billerName == null || billerName.equals("")) && (city == null || city.equals("")) &&
                (state == null || state.equals(""))){
            salaryWithNoMatch = salaryRslt;
        }
     }

     if(salary != null){
         return salary;
     } else if(salaryWithState != null){
         salary = salaryWithState;
     } else if(salaryWithName != null){
         salary = salaryWithName;
     } else if(salaryWithNoMatch != null){
         salary = salaryWithNoMatch;
     }

     return salary;

}
</code>```

EDIT: I dont want to use 3 extra variables: salaryWithState, salaryWithName,  salaryWithNoMatch.

答:
I want just to give the general idea how this can be implemented, so I haven't actually tested and checked if it will give you the right salary.</p>

```<code>public BigDecimal getSalaryForBestMatch(ResultSet resultSet, PaymentSalaryInfo paymentSalaryInfo) {
    Map<String, Supplier<String>> m1 = new HashMap<>();
    m1.put("EMP_NAME", paymentSalaryInfo::getBillerName);
    m1.put("STATE", paymentSalaryInfo::getState);
    m1.put("CITY", paymentSalaryInfo::getCity);

    Map<String, Supplier<String>> m2 = new HashMap<>();
    m2.put("STATE", paymentSalaryInfo::getState);
    m2.put("CITY", paymentSalaryInfo::getCity);

    Map<String, Supplier<String>> m3 = new HashMap<>();
    m3.put("CITY", paymentSalaryInfo::getCity);

    Optional<String> salary = Optional.empty();

    while(resultSet.next() && !salary.isPresent()) {
        salary = apply(m1, resultSet);
        //check salary and then apply(m2, resultSet) ....
    }

    return salary.isPresent() ? new BigDecimal(salary.get()) : null;
}

public Optional<String> apply(Map<String, Supplier<String>> filter, ResultSet resultSet) {
    boolean allMatch = filter.entrySet().stream().allMatch(entry -> {
        String value = resultSet.getString(entry.getKey());

        return value != null && value.equals(entry.getValue().get());
    });

    return allMatch ? Optional.of(resultSet.getString("salary")) : Optional.empty();
}
</code>```

Body:
I need to find best matched employee salary in the DB records as:

Name:   City:     State:

A       (null)    (null)

A       (null)    DEL

(null)  (null)    (null)

A        SAKET    DEL

Match order should be:

1. NAME = name, STATE = state, CITY = city

2. NAME = name, STATE = state , CITY = NULL

3. NAME = name, STATE = NULL, CITY = NULL

4. NAME = NULL, STATE = NULL, CITY = NULL

Means if in a row where all attributes matches – it should be selected, if we do not have that kind of data we should go to next best option like select state and city as NULL, etc.

My code as below, is giving me correct results but I need a more efficient way.

    private static BigDecimal getsalaryForBestMatch(ResultSet results, EmployeeRq request) throws Exception{
    BigDecimal salary = null;
    BigDecimal salaryWithState = null;
    BigDecimal salaryWithName = null;
    BigDecimal salaryWithNoMatch = null;
     while (results.next()) {

        String billerName = results.getString("EMP_NAME") != null ? results.getString("EMP_NAME").trim() : null;
        String city = results.getString("CITY") != null ? results.getString("CITY").trim() : null;
        String state = results.getString("STATE") != null ? results.getString("STATE").trim() : null;

        BigDecimal salaryRslt = null;

        if(results.getString("SALARY") != null){
            salaryRslt = BigDecimal.valueOf(results.getDouble("SALARY"));
        }
        if(billerName != null && !billerName.equals("") && billerName.equals(request.getBillPaymentsalaryCalculateInfo().getBillerName())){
            if(city != null && !city.equals("") && city.equals(request.getMsgRqHdr().getCity()) &&
                    state != null && !state.equals("") && state.equalsIgnoreCase(request.getMsgRqHdr().getstate())){
                salary = salaryRslt;
                break;
            } else if((city == null || city.equals("")) && state != null && !state.equals("") &&
                    state.equalsIgnoreCase(request.getMsgRqHdr().getState())){
                salaryWithState = salaryRslt;
            } else if((city == null || city.equals("")) && (state == null || state.equals(""))){
                salaryWithName = salaryRslt;
            }
        } else if((billerName == null || billerName.equals("")) && (city == null || city.equals("")) &&
                (state == null || state.equals(""))){
            salaryWithNoMatch = salaryRslt;
        }
     }

     if(salary != null){
         return salary;
     } else if(salaryWithState != null){
         salary = salaryWithState;
     } else if(salaryWithName != null){
         salary = salaryWithName;
     } else if(salaryWithNoMatch != null){
         salary = salaryWithNoMatch;
     }

     return salary;

}

EDIT: I dont want to use 3 extra variables: salaryWithState, salaryWithName,  salaryWithNoMatch.

Body:
I want just to give the general idea how this can be implemented, so I haven't actually tested and checked if it will give you the right salary.

public BigDecimal getSalaryForBestMatch(ResultSet resultSet, PaymentSalaryInfo paymentSalaryInfo) {
    Map<String, Supplier<String>> m1 = new HashMap<>();
    m1.put("EMP_NAME", paymentSalaryInfo::getBillerName);
    m1.put("STATE", paymentSalaryInfo::getState);
    m1.put("CITY", paymentSalaryInfo::getCity);

    Map<String, Supplier<String>> m2 = new HashMap<>();
    m2.put("STATE", paymentSalaryInfo::getState);
    m2.put("CITY", paymentSalaryInfo::getCity);

    Map<String, Supplier<String>> m3 = new HashMap<>();
    m3.put("CITY", paymentSalaryInfo::getCity);

    Optional<String> salary = Optional.empty();

    while(resultSet.next() && !salary.isPresent()) {
        salary = apply(m1, resultSet);
        //check salary and then apply(m2, resultSet) ....
    }

    return salary.isPresent() ? new BigDecimal(salary.get()) : null;
}

public Optional<String> apply(Map<String, Supplier<String>> filter, ResultSet resultSet) {
    boolean allMatch = filter.entrySet().stream().allMatch(entry -> {
        String value = resultSet.getString(entry.getKey());

        return value != null && value.equals(entry.getValue().get());
    });

    return allMatch ? Optional.of(resultSet.getString("salary")) : Optional.empty();
}


问:
Does Symfony sfLucenePlugin support the symfony1.4 using propel as ORM?
Does Symfony sfLucenePlugin support the symfony1.4 using propel as ORM?</p>

答: sfLucenePlugin integrates symfony and Zend Search Lucene to instantly add a search engine to your application. The plugin will auto-detect your ORM layer, but currently only supports Propel.</p>


问:
Objects interacting with listeners in GUI
I'm making a simple program that creates and rolls a die. There is a separate Die class which includes an argumented constructor that takes as a parameter the number of sides the die should have. What I'm having trouble with is when to create the die object. As a field I feel is too soon because I have to specify parameters in the listener method, and when it's created within the listener method, it can't be modified again in outside when the die object is called upon again to be rolled. </p>

```<code>`package question1;

    import java.awt.event.ActionEvent;
    import java.awt.event.ActionListener;
    import javax.swing.JButton;
    import javax.swing.JEditorPane;
    import javax.swing.JFrame;
    import javax.swing.JLabel;
    import javax.swing.JPanel;
    import javax.swing.JTextArea;
    import javax.swing.JTextField;

/**
   This frame shows a data set and its statistics.
 */
    public class DieGUI extends JFrame
    {
        private static int WINDOW_WIDTH = 450;
        private static int WINDOW_HEIGHT = 250;
        private JLabel message;
        private JTextField Sides;
        private JTextArea data;
        private JButton create;
        private JButton rollButton;
        private static JPanel panel;
        private int numSides;

    //declare data fields here (GUI Components and other data fields)

    public DieGUI()
    {

        message = new JLabel("Enter number of sides");
        Sides = new JTextField(5);
        create = new JButton("Create");
        rollButton = new JButton("Roll Current Die");
        data = new JTextArea(10, 30);

        panel = new JPanel();
        panel.add(message);
        panel.add(Sides);
        panel.add(create);
        panel.add(rollButton);
        panel.add(data);

        //Initialize data fields and construct GUI

    //supporting methods are here.
    create.addActionListener(new ActionListener(){

            @Override
            public void actionPerformed(ActionEvent arg0) {
                numSides = Integer.parseInt(Sides.getText());

    data.append("Note that creating a new die     replaces the current one");

                Die die = new Die(numSides);
                data.append("\n" + die.toString());
            }
        });

    rollButton.addActionListener(new ActionListener(){

    @Override
    public void actionPerformed(ActionEvent arg1){
        die.roll();
        data.append("\n" + die.getSideUp());
    }
    });
        }

    public static void main(String[] args)
    {

        JFrame frame = new DieGUI();
        frame.setTitle("Dice GUI!");
        frame.setSize(WINDOW_WIDTH, WINDOW_HEIGHT);
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.setVisible(true);
        frame.add(panel);
    }}`
</code>```

答:
There are any number of ways to solve this:

Add the die as field with a default number of faces.  Add a method,
setFaceCount() to the Die class to update this as necessary from
your listener.

Add a die field, but set to null as default.  Replace die
    in your listener.

Regardless, you'll need to create a die field, so that it can be accessed outside of the scope of your listener method.  How you design it will depend on what behavior you want in your GUI.

Body:
I'm making a simple program that creates and rolls a die. There is a separate Die class which includes an argumented constructor that takes as a parameter the number of sides the die should have. What I'm having trouble with is when to create the die object. As a field I feel is too soon because I have to specify parameters in the listener method, and when it's created within the listener method, it can't be modified again in outside when the die object is called upon again to be rolled.

`package question1;

    import java.awt.event.ActionEvent;
    import java.awt.event.ActionListener;
    import javax.swing.JButton;
    import javax.swing.JEditorPane;
    import javax.swing.JFrame;
    import javax.swing.JLabel;
    import javax.swing.JPanel;
    import javax.swing.JTextArea;
    import javax.swing.JTextField;

/**
   This frame shows a data set and its statistics.
 */
    public class DieGUI extends JFrame
    {
        private static int WINDOW_WIDTH = 450;
        private static int WINDOW_HEIGHT = 250;
        private JLabel message;
        private JTextField Sides;
        private JTextArea data;
        private JButton create;
        private JButton rollButton;
        private static JPanel panel;
        private int numSides;

    //declare data fields here (GUI Components and other data fields)

    public DieGUI()
    {

        message = new JLabel("Enter number of sides");
        Sides = new JTextField(5);
        create = new JButton("Create");
        rollButton = new JButton("Roll Current Die");
        data = new JTextArea(10, 30);

        panel = new JPanel();
        panel.add(message);
        panel.add(Sides);
        panel.add(create);
        panel.add(rollButton);
        panel.add(data);

        //Initialize data fields and construct GUI

    //supporting methods are here.
    create.addActionListener(new ActionListener(){

            @Override
            public void actionPerformed(ActionEvent arg0) {
                numSides = Integer.parseInt(Sides.getText());

    data.append("Note that creating a new die     replaces the current one");

                Die die = new Die(numSides);
                data.append("\n" + die.toString());
            }
        });

    rollButton.addActionListener(new ActionListener(){

    @Override
    public void actionPerformed(ActionEvent arg1){
        die.roll();
        data.append("\n" + die.getSideUp());
    }
    });
        }

    public static void main(String[] args)
    {

        JFrame frame = new DieGUI();
        frame.setTitle("Dice GUI!");
        frame.setSize(WINDOW_WIDTH, WINDOW_HEIGHT);
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.setVisible(true);
        frame.add(panel);
    }}`


答:
If you're using already using webpack you can have a look at html-webpack-plugin. It will create a .html file with your bundles added as script tags.

html-webpack-plugin in conjunction with creating a vendor bundle should help with this problem.

Title: How to automatically include NPM "dependencies" into index.html through <script> tags in VUE JS WEBPACK project?

Body:
I know there is a GRUNT-BOWER plugin which automatically includes the BOWER dependencies into index.html file through  tags every time you install any new bower package.

Is there any similar tool which automatically Injects / includes the NPM dependencies into index.html ?

FYI the project is a VUE-CLI WEBPACK project. Can this be achieved through WEBPACK or do i need a dedicated build tool for doing it ?


问:
Error while joining two tables in laravel controller
Joining two tables showing error:

```<code>"SQLSTATE[42000]: Syntax error or access violation: 1103 Incorrect table name 'transaction_master ' "
</code>```

But in my database transaction_master is exists.

The following query:

```<code>$trans_results= DB::table('report_master as rm')->join('transaction_master ', 'transaction_master.id','=','rm.id')->select('transaction_master.name as transactionID')->get();
</code>```

答:
try this

```<code>DB::table('report_master')
    ->join('transaction_master', 'report_master.id', '=', 'transaction_master.id')
    ->select('transaction_master.name as transactionID')
    ->get();
</code>```

Read - Laravel Query Builder Joins

Body:
Joining two tables showing error:

"SQLSTATE[42000]: Syntax error or access violation: 1103 Incorrect table name 'transaction_master ' "

But in my database transaction_master is exists.

The following query:

$trans_results= DB::table('report_master as rm')->join('transaction_master ', 'transaction_master.id','=','rm.id')->select('transaction_master.name as transactionID')->get();

Body:
try this

DB::table('report_master')
    ->join('transaction_master', 'report_master.id', '=', 'transaction_master.id')
    ->select('transaction_master.name as transactionID')
    ->get();

Read - Laravel Query Builder Joins