问:
CSS Selector issue with list items
I am facing a problem with CSS selector. I have content in "list Items(LI)" and "list Items(LI)" having class"child". I need to style for first "list Items(LI)" with the class name ".child". only in CSS.

ul{margin:0;padding:0 32px 0 32px}
li{ color:red;}
.child{
  color:green;
  background:red;
  width:100%;
}
li.child ~ .child{
  color:#fff;
  font-size:20px;
  background:green;
  width:10px;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><ul>
  <li>hellow</li>
  <li>hellow</li>
  <li>hellow</li>
  <li>hellow</li>
  <li>hellow</li>
  <li>hellow</li>
  <li>hellow</li>
  <li class="child">
This need to be Red Color
  </li>
  <li class="child">sub text</li>
  <li class="child">sub text</li>
  <li class="child">sub text</li>
  <li></li>
  <li></li>
  <li></li>
  <li></li>
  <li></li>
  <li></li>
  <li></li>
  <li></li>
  <li></li>
</ul></code>```

答:
you want like this actually you have to take another
 because you're not targetting first-child of '' in the middle you want or else you can use :nth-child(8) without adding other
 list.

ul{margin:0;padding:0 32px 0 32px}
li{ color:red;}
.child{
  color:green;
}
li.child:first-child{
  color:blue;
  font-size:20px;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><ul>
  <li>hellow</li>
  <li>hellow</li>
  <li>hellow</li>
  <li>hellow</li>
  <li>hellow</li>
  <li>hellow</li>
  <li>hellow</li>
  </ul>
  <ul>
  <li class="child">
  sub
  <div>
  I want differnt styles for this.
  </div>
  </li>
  <li class="child">sub text</li>
  <li class="child">sub text</li>
  <li class="child">sub text</li>
</ul></code>```

Title: CSS Selector issue with list items

Body:
I am facing a problem with CSS selector. I have content in "list Items(LI)" and "list Items(LI)" having class"child". I need to style for first "list Items(LI)" with the class name ".child". only in CSS.

ul{margin:0;padding:0 32px 0 32px}
li{ color:red;}
.child{
  color:green;
  background:red;
  width:100%;
}
li.child ~ .child{
  color:#fff;
  font-size:20px;
  background:green;
  width:10px;
}

hellow

hellow

hellow

hellow

hellow

hellow

hellow

This need to be Red Color

sub text

sub text

sub text

Body:
you want like this actually you have to take another <ul> because you're not targetting first-child of '' in the middle you want or else you can use :nth-child(8) without adding other <ul> list.

ul{margin:0;padding:0 32px 0 32px}
li{ color:red;}
.child{
  color:green;
}
li.child:first-child{
  color:blue;
  font-size:20px;
}

<ul>
  <li>hellow</li>
  <li>hellow</li>
  <li>hellow</li>
  <li>hellow</li>
  <li>hellow</li>
  <li>hellow</li>
  <li>hellow</li>
  </ul>
  <ul>
  <li class="child">
  sub
  <div>
  I want differnt styles for this.
  </div>
  </li>
  <li class="child">sub text</li>
  <li class="child">sub text</li>
  <li class="child">sub text</li>
</ul>


来源: stackexchange

问:
Matlab : color code portion of the line
I have the following array that contains ALL of my points:

x = [1,2,3,4,5,6,7,8,9,10,11,12,13,14,15];

y = [1,9,8,5,2,8,1,4,3,11,13,15,16,13,12];

I plot my blue line with the following command:

```<code>plot(x,y, 'blue');
</code>```

I want to color code sections of the generated plot.

Example:

x1 = [2,3,4,11,12,13];

numbers in x range of x1 should be red on the x axis on the original plot.

Looking at this post , it is recommended by the author to draw out different lines, based on some qualifying boolean.

Hence, I have updated my code to be as follows:

```<code>x = [1,2,3,4,5,6,7,8,9,10,11,12,13,14,15];
y = [1,9,8,5,2,8,1,4,3,11,13,15,16,13,12];
x1 = [2,3,4,11,12,13];

canPlot = ismember(x, x1);
hold on;
plot(x,y, 'blue');
plot(x(canPlot), y(canPlot), 'red');
hold off;
</code>```

However, the generated graph connects "disconnected" points. Here is a photo of the problem:

As you can see above, the two segments x1 when it equates to 4 and x1 when it equates to 11 are connected. I don't want them to be connected. How can I get rid of that connecting line without splitting x1 into to sequential variables?

I.e

These points should be connected to formulate a red line:

2,3,4

11,12,13

These points should not be connected to formulate a red line:

4,11

答:
You can use NaN as a delimiter between the sequential values in your vector to plot, and then plot divide it into seperated lines.

I don't know about a comfort way in Matlab to append and add values in the middle of a vector, so I'll create a new vector of NaN's and then will copy the desired values to the matching indices:

```<code>x = [1,2,3,4,5,6,7,8,9,10,11,12,13,14,15];
y = [1,9,8,5,2,8,1,4,3,11,13,15,16,13,12];
x1 = [2,3,4,11,12,13];

xPlot=nan(1,length(x1)+sum(diff(x1)>1));
xPlot((1:length(x1))+[0 cumsum(diff(x1)>1)])=x(ismember(x,x1));
yPlot=nan(1,length(x1)+sum(diff(x1)>1));
yPlot((1:length(x1))+[0 cumsum(diff(x1)>1)])=y(ismember(x,x1));
figure; plot(x,y,'b')
hold on; plot(xPlot,yPlot,'r')
</code>```

ContentLicense: CC BY-SA 3.0

Title: Matlab : color code portion of the line

Body:
I have the following array that contains ALL of my points:

x = [1,2,3,4,5,6,7,8,9,10,11,12,13,14,15];

y = [1,9,8,5,2,8,1,4,3,11,13,15,16,13,12];

I plot my blue line with the following command:

plot(x,y, 'blue');

I want to color code sections of the generated plot.

Example:

x1 = [2,3,4,11,12,13];

numbers in x range of x1 should be red on the x axis on the original plot.

Looking at this post , it is recommended by the author to draw out different lines, based on some qualifying boolean.

Hence, I have updated my code to be as follows:

x = [1,2,3,4,5,6,7,8,9,10,11,12,13,14,15];
y = [1,9,8,5,2,8,1,4,3,11,13,15,16,13,12];
x1 = [2,3,4,11,12,13];

canPlot = ismember(x, x1);
hold on;
plot(x,y, 'blue');
plot(x(canPlot), y(canPlot), 'red');
hold off;

However, the generated graph connects "disconnected" points. Here is a photo of the problem:

As you can see above, the two segments x1 when it equates to 4 and x1 when it equates to 11 are connected. I don't want them to be connected. How can I get rid of that connecting line without splitting x1 into to sequential variables?

I.e

These points should be connected to formulate a red line:

2,3,4

11,12,13

These points should not be connected to formulate a red line:

4,11

Body:
You can use NaN as a delimiter between the sequential values in your vector to plot, and then plot divide it into seperated lines.

I don't know about a comfort way in Matlab to append and add values in the middle of a vector, so I'll create a new vector of NaN's and then will copy the desired values to the matching indices:

x = [1,2,3,4,5,6,7,8,9,10,11,12,13,14,15];
y = [1,9,8,5,2,8,1,4,3,11,13,15,16,13,12];
x1 = [2,3,4,11,12,13];

xPlot=nan(1,length(x1)+sum(diff(x1)>1));
xPlot((1:length(x1))+[0 cumsum(diff(x1)>1)])=x(ismember(x,x1));
yPlot=nan(1,length(x1)+sum(diff(x1)>1));
yPlot((1:length(x1))+[0 cumsum(diff(x1)>1)])=y(ismember(x,x1));
figure; plot(x,y,'b')
hold on; plot(xPlot,yPlot,'r')


问:
Copy Data from many workbooks to a master using column headers
Below code is working beautifully for copying data from ONE workbook to my master (Source.xlsx). Can I modify this code to do the same for many workbooks?
I need data from many files in one directory to be appended to that table, using the column headers in the source. Files I am copying from always have the headers I am looking for, but in different columns.
It would be super useful to save the file name that the data was copied from along with the subfolder and subfolder2 saved in added columns (master file location > subfolder > subfolder2 > files to copy from).
Can you please help me StackOverflow gurus?</p>

```<code>Sub CopyByHeader()

    Dim CurrentWS As Worksheet
    Set CurrentWS = ActiveSheet

    Dim SourceWS As Worksheet
    Set SourceWS = Workbooks("vavc1.valor.carnival.com_2017-10-30.xls").Worksheets(1)
    Dim SourceHeaderRow As Integer: SourceHeaderRow = 1
    Dim SourceCell As Range

    Dim TargetWS As Worksheet
    Set TargetWS = Workbooks("Source.xlsx").Worksheets(1)
    Dim TargetHeader As Range
    Set TargetHeader = TargetWS.Range("A1:K1")

    Dim RealLastRow As Long
    Dim SourceCol As Integer

    SourceWS.Activate
    For Each Cell In TargetHeader
        If Cell.Value <> "" Then
            Set SourceCell = Rows(SourceHeaderRow).Find _
                (Cell.Value, LookIn:=xlValues, LookAt:=xlWhole)
            If Not SourceCell Is Nothing Then
                SourceCol = SourceCell.Column
                RealLastRow = Columns(SourceCol).Find("*", LookIn:=xlValues, _
                SearchOrder:=xlByRows, SearchDirection:=xlPrevious).Row
                If RealLastRow > SourceHeaderRow Then
                    Range(Cells(SourceHeaderRow + 1, SourceCol), Cells(RealLastRow, _
                        SourceCol)).Copy
                    TargetWS.Cells(2, Cell.Column).PasteSpecial xlPasteValues
                End If
            End If
        End If
    Next

    CurrentWS.Activate

End Sub
</code>```

答:
So you need to wrap your code that works in a loop. For each workbook in folder.files, run your code.

This post will tell you how to iterate over the workbooks in a folder:

Loop through files in a folder using VBA?

Body:
Below code is working beautifully for copying data from ONE workbook to my master (Source.xlsx). Can I modify this code to do the same for many workbooks?
I need data from many files in one directory to be appended to that table, using the column headers in the source. Files I am copying from always have the headers I am looking for, but in different columns.
It would be super useful to save the file name that the data was copied from along with the subfolder and subfolder2 saved in added columns (master file location > subfolder > subfolder2 > files to copy from).
Can you please help me StackOverflow gurus?

Sub CopyByHeader()

    Dim CurrentWS As Worksheet
    Set CurrentWS = ActiveSheet

    Dim SourceWS As Worksheet
    Set SourceWS = Workbooks("vavc1.valor.carnival.com_2017-10-30.xls").Worksheets(1)
    Dim SourceHeaderRow As Integer: SourceHeaderRow = 1
    Dim SourceCell As Range

    Dim TargetWS As Worksheet
    Set TargetWS = Workbooks("Source.xlsx").Worksheets(1)
    Dim TargetHeader As Range
    Set TargetHeader = TargetWS.Range("A1:K1")

    Dim RealLastRow As Long
    Dim SourceCol As Integer

    SourceWS.Activate
    For Each Cell In TargetHeader
        If Cell.Value <> "" Then
            Set SourceCell = Rows(SourceHeaderRow).Find _
                (Cell.Value, LookIn:=xlValues, LookAt:=xlWhole)
            If Not SourceCell Is Nothing Then
                SourceCol = SourceCell.Column
                RealLastRow = Columns(SourceCol).Find("*", LookIn:=xlValues, _
                SearchOrder:=xlByRows, SearchDirection:=xlPrevious).Row
                If RealLastRow > SourceHeaderRow Then
                    Range(Cells(SourceHeaderRow + 1, SourceCol), Cells(RealLastRow, _
                        SourceCol)).Copy
                    TargetWS.Cells(2, Cell.Column).PasteSpecial xlPasteValues
                End If
            End If
        End If
    Next

    CurrentWS.Activate

End Sub


问:
Get-mailboxstatistics from all Office 365 Mailboxes
I need the LastLogonTime from all our cloud hosted mailboxes. Google tells me to

```<code>Get-Mailbox | Get-MailboxStatistics
</code>```

Get-Mailbox currently returns 2172 mailboxes but when returning the entire object to Get-MailboxStatistics, it's giving an error on 59 mailboxes: The specified mailbox "Firstname Lastname"  isn't unique.

For some of these mailboxes I can indeed find a Mailbox with a duplicate DisplayName but not for all.

So there are some Mailboxes without a valid Get-MailboxStatistics result. But when I ask the Get-MailboxStatistics from the ExchangeGuid, the record IS returned. I.e.

```<code>Get-MailboxStatistics -Identity 7045326a-5c0f-4a84-aa0c-ceb$$$$c67fe
</code>```

When I modify my script to loop the mailbox results and query the statistics for each mailbox, I get the (obvious) response: The request is not serviced on the server. Your request is too frequent. Please wait for few minutes and retry again.

So.. my question is..
How do I pipe the ExchangeGuid of every Get-Mailbox record to the Get-MailboxStatistics?

```<code>Get-Mailbox -ResultSize 5 | Select-Object ExchangeGuid | Get-MailboxStatistics
</code>```

returns:

```<code>The input object cannot be bound to any parameters for the command either because the command does not take pipeline in put or the input and its properties do not match any of the parameters that take pipeline input.
    + CategoryInfo          : InvalidArgument: (@{ExchangeGuid=...5-684390d4a758}:PSObject) [Get-MailboxStatistics], P    arameterBindingException
    + FullyQualifiedErrorId : InputObjectNotBound,Get-MailboxStatistics
    + PSComputerName        : outlook.office365.com
</code>```

答:
You can try to use the UPN (User Principal Name) which is unique :

get-mailbox -ResultSize 5 |select -expand userprincipalname |Get-MailboxStatistics

Body:
I need the LastLogonTime from all our cloud hosted mailboxes. Google tells me to

Get-Mailbox | Get-MailboxStatistics

Get-Mailbox currently returns 2172 mailboxes but when returning the entire object to Get-MailboxStatistics, it's giving an error on 59 mailboxes: The specified mailbox "Firstname Lastname"  isn't unique.

For some of these mailboxes I can indeed find a Mailbox with a duplicate DisplayName but not for all.

So there are some Mailboxes without a valid Get-MailboxStatistics result. But when I ask the Get-MailboxStatistics from the ExchangeGuid, the record IS returned. I.e.

Get-MailboxStatistics -Identity 7045326a-5c0f-4a84-aa0c-ceb$$$$c67fe

When I modify my script to loop the mailbox results and query the statistics for each mailbox, I get the (obvious) response: The request is not serviced on the server. Your request is too frequent. Please wait for few minutes and retry again.

So.. my question is..
How do I pipe the ExchangeGuid of every Get-Mailbox record to the Get-MailboxStatistics?

Get-Mailbox -ResultSize 5 | Select-Object ExchangeGuid | Get-MailboxStatistics

returns:

The input object cannot be bound to any parameters for the command either because the command does not take pipeline in put or the input and its properties do not match any of the parameters that take pipeline input.
    + CategoryInfo          : InvalidArgument: (@{ExchangeGuid=...5-684390d4a758}:PSObject) [Get-MailboxStatistics], P    arameterBindingException
    + FullyQualifiedErrorId : InputObjectNotBound,Get-MailboxStatistics
    + PSComputerName        : outlook.office365.com


问:
$[object Object]-$[object Object] Couldn't retrieve the value
I have a problem where I couldn't retrieve the slider value when I load the page, it just shows me $[object Object]-$[object Object]. How do I fixed the code?</p>

```<code>$( function(){
$("#slider-range").slider({
   range:true,
   min:0.00,
   max:499.00,
   values:[0.00, 499.00],
   slide: function(event, ui){
       $("#amount").val("$" + ui.values[0] + "-$" + ui.values[1]);
   }
});
$("#amount").val("$" + $("slider-range").slider("values",0) + "-$" + $("slider-range").slider("values", 1));
</code>```

答:
Check this..</p>

```<code>$( function() {
    $( "#slider-range" ).slider({
      range: true,
      min: 0,
      max: 499,
      values: [ 0, 499],
      slide: function( event, ui ) {
        $( "#amount" ).val( "$" + ui.values[ 0 ] + " - $" + ui.values[ 1 ] );
      }
    });
    $( "#amount" ).val( "$" + $( "#slider-range" ).slider( "values", 0 ) +
      " - $" + $( "#slider-range" ).slider( "values", 1 ) );
});
</code>```

Body:
I have a problem where I couldn't retrieve the slider value when I load the page, it just shows me $[object Object]-$[object Object]. How do I fixed the code?

$( function(){
$("#slider-range").slider({
   range:true,
   min:0.00,
   max:499.00,
   values:[0.00, 499.00],
   slide: function(event, ui){
       $("#amount").val("$" + ui.values[0] + "-$" + ui.values[1]);
   }
});
$("#amount").val("$" + $("slider-range").slider("values",0) + "-$" + $("slider-range").slider("values", 1));

Body:
Check this..

$( function() {
    $( "#slider-range" ).slider({
      range: true,
      min: 0,
      max: 499,
      values: [ 0, 499],
      slide: function( event, ui ) {
        $( "#amount" ).val( "$" + ui.values[ 0 ] + " - $" + ui.values[ 1 ] );
      }
    });
    $( "#amount" ).val( "$" + $( "#slider-range" ).slider( "values", 0 ) +
      " - $" + $( "#slider-range" ).slider( "values", 1 ) );
});


问:
Type mismatch: cannot convert from double to int
Need to write a program to calculate sum of all digits and then give results when the total sum vaue ends with 5 or 8.Please help correct this code!</p>

```<code>import java.util.Scanner;
public class Main {

    public static void main(String[] args) {

        Scanner in= new Scanner(System.in);
        int customerID = in.nextInt();
        while(customerID > 0)
        {
        int Reminder = customerID % 10;
        int sum = sum+ Reminder;
        customerID = customerID / 10;
        }
        if(sum%5||sum%8)
        {
        System.out.println("Lucky Customer");
        }else
        {
        System.out.println("Unlucky Customer");
        }
        if(sum <0)
        {
        System.out.println("Invalid Input");
        }
        }
        }
</code>```

答:
Apart from the fact that this code doesn't produce the error you've mentioned, there are other issues with the code. I've tried to address them instead.</p>

```<code>public static void main(String[] args) {
    Scanner in= new Scanner(System.in);
    int customerID = in.nextInt();
    int sum = 0;
    // sum needs to be initialized outside the while loop
    // or else you wouldn't be able to use it outside it
    while(customerID > 0) {
        int Reminder = customerID % 10;
        sum = sum+ Reminder;
        customerID = customerID / 10;
    }
    if(sum%5 == 0 || sum%8 == 0) {
        //You cannot use int as a condition in if
        System.out.println("Lucky Customer");
    } else {
        System.out.println("Unlucky Customer");
    }
    if(sum <0) {
        System.out.println("Invalid Input");
    }
}
</code>```

Body:
Need to write a program to calculate sum of all digits and then give results when the total sum vaue ends with 5 or 8.Please help correct this code!

import java.util.Scanner;
public class Main {

    public static void main(String[] args) {

        Scanner in= new Scanner(System.in);
        int customerID = in.nextInt();
        while(customerID > 0)
        {
        int Reminder = customerID % 10;
        int sum = sum+ Reminder;
        customerID = customerID / 10;
        }
        if(sum%5||sum%8)
        {
        System.out.println("Lucky Customer");
        }else
        {
        System.out.println("Unlucky Customer");
        }
        if(sum <0)
        {
        System.out.println("Invalid Input");
        }
        }
        }

Body:
Apart from the fact that this code doesn't produce the error you've mentioned, there are other issues with the code. I've tried to address them instead.

public static void main(String[] args) {
    Scanner in= new Scanner(System.in);
    int customerID = in.nextInt();
    int sum = 0;
    // sum needs to be initialized outside the while loop
    // or else you wouldn't be able to use it outside it
    while(customerID > 0) {
        int Reminder = customerID % 10;
        sum = sum+ Reminder;
        customerID = customerID / 10;
    }
    if(sum%5 == 0 || sum%8 == 0) {
        //You cannot use int as a condition in if
        System.out.println("Lucky Customer");
    } else {
        System.out.println("Unlucky Customer");
    }
    if(sum <0) {
        System.out.println("Invalid Input");
    }
}


问:
Debugging gdb - listing source directories in use
Trying to debug an ada program, gdb doesn't seem to be able to locate a source. I did confirm that the running executable was the same one that was just built. Upon attach, it displays the following in the console, when instead it should take me to the current location in the source code:

```<code>(gdb) attach 804
0x0000003de620b68c in ?? ()
(gdb) frame 1
#1  0x0000000000000000 in ?? ()
(gdb) frame 0
#0  0x0000003de620b68c in ?? ()
</code>```

Is there a way to get the gdb to tell me which source directories it is using? Or is there another way I can troubleshoot this issue?

I am launching this out of GPS 2017 (20170515) hosted on x86_64-pc-linux-gnu
GNAT Pro 6.4.2 (20110614-45).

答:
It seems that you have not given gdb the symbol table or your program is stripped.

When you attach to a program, you should tell gdb what executable you attach so that it reads the symbol table.  You should have compiled your program with -g (debugging support) and make sure the link pass does not strip symbols.  Then, run gdb as follows:

```<code>gdb myprog -p 804
</code>```

But you can also run without attaching (which is whay you did) and then attach.

```<code>gdb myprog
GNU gdb (GDB) 7.10 for GNAT GPL 2017 [rev=gdb-7.10-ref-199-g7cfc608]
Copyright (C) 2015 Free Software Foundation, Inc.
License GPLv3+: GNU GPL version 3 or later
<http://gnu.org/licenses/gpl.html>
This is free software: you are free to change and redistribute it.
See your support agreement for details of warranty and support.
If you do not have a current support agreement, then there is absolutely
no warranty for this version of GDB.  Type "show copying"
and "show warranty" for details.
This GDB was configured as "x86_64-pc-linux-gnu".
Type "show configuration" for configuration details.For help, type "help".
Type "apropos word" to search for commands related to "word"...
Reading symbols from prog...done.
(gdb) attach 804
</code>```

You can also use the symbol-file command to tell gdb what program file
to run:

```<code>(gdb) symbol-file myprog
Reading symbols from myprog...done.
</code>```

If your program is stripped, gdb will print

```<code>Reading symbols from prog...(no debugging symbols found)...done.
</code>```

Having your symbol table read, you can list the source files that are recognized by gdb by using info sources command.  This tells you the source files that have been identified in the symbol table.

```<code>(gdb) info sources
Source files for which symbols have been read in:

.../b__myprog.adb,
.../b__myprog.ads,
/build/eglibc-SvCtMH/eglibc-2.19/elf/rtld.c,
/build/eglibc-SvCtMH/eglibc-2.19/elf/../sysdeps/generic/_itoa.h,
/build/eglibc-SvCtMH/eglibc-2.19/elf/../sysdeps/unix/sysv/linux/dl-osinfo.h,
...
</code>```

Another interesting command you may use is info files.  This tells you the program sections that have been identified with the associated symbol file.  If you have dynamic libraries, you should also see them there.

```<code>(gdb) info files
Symbols from "myprog".
Native process:
    Using the running image of child Thread 0x7ffff7fb4780 (LWP 32214).
    While running this, GDB does not access memory from...
Local exec file:
    `myprog', file type elf64-x86-64.
    Entry point: 0x40ac5e
    0x0000000000400238 - 0x0000000000400254 is .interp
    0x0000000000400254 - 0x0000000000400274 is .note.ABI-tag
    0x0000000000400278 - 0x0000000000400cb4 is .hash
    0x0000000000400cb8 - 0x0000000000403148 is .dynsym
    0x0000000000403148 - 0x00000000004046b5 is .dynstr
    0x00000000004046b6 - 0x00000000004049c2 is .gnu.version
...
</code>```

Body:
Trying to debug an ada program, gdb doesn't seem to be able to locate a source. I did confirm that the running executable was the same one that was just built. Upon attach, it displays the following in the console, when instead it should take me to the current location in the source code:

(gdb) attach 804
0x0000003de620b68c in ?? ()
(gdb) frame 1
#1  0x0000000000000000 in ?? ()
(gdb) frame 0
#0  0x0000003de620b68c in ?? ()

Is there a way to get the gdb to tell me which source directories it is using? Or is there another way I can troubleshoot this issue?

I am launching this out of GPS 2017 (20170515) hosted on x86_64-pc-linux-gnu
GNAT Pro 6.4.2 (20110614-45).

Body:
It seems that you have not given gdb the symbol table or your program is stripped.

When you attach to a program, you should tell gdb what executable you attach so that it reads the symbol table.  You should have compiled your program with -g (debugging support) and make sure the link pass does not strip symbols.  Then, run gdb as follows:

gdb myprog -p 804

But you can also run without attaching (which is whay you did) and then attach.

gdb myprog
GNU gdb (GDB) 7.10 for GNAT GPL 2017 [rev=gdb-7.10-ref-199-g7cfc608]
Copyright (C) 2015 Free Software Foundation, Inc.
License GPLv3+: GNU GPL version 3 or later
<http://gnu.org/licenses/gpl.html>
This is free software: you are free to change and redistribute it.
See your support agreement for details of warranty and support.
If you do not have a current support agreement, then there is absolutely
no warranty for this version of GDB.  Type "show copying"
and "show warranty" for details.
This GDB was configured as "x86_64-pc-linux-gnu".
Type "show configuration" for configuration details.For help, type "help".
Type "apropos word" to search for commands related to "word"...
Reading symbols from prog...done.
(gdb) attach 804

You can also use the symbol-file command to tell gdb what program file
to run:

(gdb) symbol-file myprog
Reading symbols from myprog...done.

If your program is stripped, gdb will print

Reading symbols from prog...(no debugging symbols found)...done.

Having your symbol table read, you can list the source files that are recognized by gdb by using info sources command.  This tells you the source files that have been identified in the symbol table.

(gdb) info sources
Source files for which symbols have been read in:

.../b__myprog.adb,
.../b__myprog.ads,
/build/eglibc-SvCtMH/eglibc-2.19/elf/rtld.c,
/build/eglibc-SvCtMH/eglibc-2.19/elf/../sysdeps/generic/_itoa.h,
/build/eglibc-SvCtMH/eglibc-2.19/elf/../sysdeps/unix/sysv/linux/dl-osinfo.h,
...

Another interesting command you may use is info files.  This tells you the program sections that have been identified with the associated symbol file.  If you have dynamic libraries, you should also see them there.

(gdb) info files
Symbols from "myprog".
Native process:
    Using the running image of child Thread 0x7ffff7fb4780 (LWP 32214).
    While running this, GDB does not access memory from...
Local exec file:
    `myprog', file type elf64-x86-64.
    Entry point: 0x40ac5e
    0x0000000000400238 - 0x0000000000400254 is .interp
    0x0000000000400254 - 0x0000000000400274 is .note.ABI-tag
    0x0000000000400278 - 0x0000000000400cb4 is .hash
    0x0000000000400cb8 - 0x0000000000403148 is .dynsym
    0x0000000000403148 - 0x00000000004046b5 is .dynstr
    0x00000000004046b6 - 0x00000000004049c2 is .gnu.version
...


问:
Difference between x.toString() and x+""
Back in college one of my profs. taught us to just do x + "" as a quick conversion from basic types to strings.

I don't remember which class it was in I had him for some Java and C++ courses(I haven't used either for some time now), but I use it in C#/.Net now which is what I'm primarily developing in lately.

Is there an advantage to using .toString() over +"" for basic types such at int, decimal, float...?
What cases would .toString() be better?

Note:I was shown .toString() as well, that prof just recommended +"" because it was shorter and I have just done that since then without questioning it.

答:
There are no advantages or disadvantages of using x+"". toString is the method of Object type which implicitly called every time you add any object to string.

You can always override this method in your class if you'd like.

ContentLicense: CC BY-SA 2.5


问:
merge two pandas data frame and skip common columns of right
I am using pandas DataFrame as a lightweight dataset to maintain some status and need to dynamically/continuously merge new DataFrames into existing table. Say I have two datasets as below:

df1:

```<code>   a  b
0  0  1
1  2  3
2  4  5
3  6  7
4  8  9
</code>```

df2:

```<code>    b   c
0  10  11
1  12  13
2  14  15
3  16  17
4  18  19
</code>```

I want to merge df2 to df1 (on index), and for columns in common (in this case, it is 'b'), simply discard the common column of df2.

```<code>   a  b   c
0  0  1  11
1  2  3  13
2  4  5  15
3  6  7  17
4  8  9  19
</code>```

My code was checking common part between df1 and df2 by using SET， so that I manually drop common part in df2. I wonder is there any much efficient way to do this?

答:
Pandas merge function will also work wonders. You can do it as:

```<code>pd.merge(left=df1, right=df2, how='inner')

   a  b   c
0  0  1  11
1  2  3  13
2  4  5  15
3  6  7  17
4  8  9  19
</code>```

by eliminating the 'on' attribute of merge function it will consider the columns which are in-common in both of the dataframes.

Body:
I am using pandas DataFrame as a lightweight dataset to maintain some status and need to dynamically/continuously merge new DataFrames into existing table. Say I have two datasets as below:

df1:

   a  b
0  0  1
1  2  3
2  4  5
3  6  7
4  8  9

df2:

    b   c
0  10  11
1  12  13
2  14  15
3  16  17
4  18  19

I want to merge df2 to df1 (on index), and for columns in common (in this case, it is 'b'), simply discard the common column of df2.

   a  b   c
0  0  1  11
1  2  3  13
2  4  5  15
3  6  7  17
4  8  9  19

My code was checking common part between df1 and df2 by using SET， so that I manually drop common part in df2. I wonder is there any much efficient way to do this?

Body:
Pandas merge function will also work wonders. You can do it as:

pd.merge(left=df1, right=df2, how='inner')

   a  b   c
0  0  1  11
1  2  3  13
2  4  5  15
3  6  7  17
4  8  9  19

by eliminating the 'on' attribute of merge function it will consider the columns which are in-common in both of the dataframes.


问:
Hash and encode variable before sending along with request
I'm trying to setup JMeter for connecting to a service which requires some hashing be done on some variables before I start and in-between requests.

I've created a User Defined Variable that has the authentication info in plain text.

Before the first HTTP Request is called I need to hash the password using SHA256, encode it using base64 and then convert to uppercase.

I will receive an auth_token within a JSON formated response body. Then I  need to do the same SHA256 -> base64 -> uppercase chain to that auth_token and from then on it will be used in the request header.

答:
There's a new function __digest, currently in nightly builds

In your case to save in encodedValue variable the result of password variable use the following:

```<code>${__digest(SHA-256,${password},,,encodedValue)}
</code>```

You can download Custom JMeter Functions plugin to call base 64 encoding function:

```<code>${__base64Encode(encodedValue, base64Value)}
</code>```

And then call uppercase function:

```<code>${__uppercase(base64Value, finalValue)}
</code>```

${finalValue} will hold the final value of this operations

Body:
There's a new function __digest, currently in nightly builds

In your case to save in encodedValue variable the result of password variable use the following:

${__digest(SHA-256,${password},,,encodedValue)}

You can download Custom JMeter Functions plugin to call base 64 encoding function:

${__base64Encode(encodedValue, base64Value)}

And then call uppercase function:

${__uppercase(base64Value, finalValue)}

${finalValue} will hold the final value of this operations


问:
Does the LIBELAS depend on camera parameters?
I want to use LIBELAS(Library for Efficient Large-scale Stereo Matching) to generate the disparity map. My stereo camera has 25 cm baseline and 12mm focal length. I cannot generate sufficient disparity map for my stereo images? Could you please guide me why the disparity map is noisy? Does ELAS library depend on camera parameters?
Best Regards</p>

答:
I think this library LIBELAS caliculates disparity for each pixel between stereo image pairs. It does not depend on camera parameter.
So the reason why you can't generate clean disparity is too few feature on the image to find. Only expanding the image resolution is the way to solve this.

By the way, Depth is calculated by disparity, focus length and baseline as following.

```<code>depth = baseline * focus_length / disparity
</code>```

Body:
I think this library LIBELAS caliculates disparity for each pixel between stereo image pairs. It does not depend on camera parameter.
So the reason why you can't generate clean disparity is too few feature on the image to find. Only expanding the image resolution is the way to solve this.

By the way, Depth is calculated by disparity, focus length and baseline as following.

depth = baseline * focus_length / disparity


问:
iOS Launchscreen is not being displayed in Xamarin.Forms
I don't know what happened but since some days ago the LaunchScreen is not being displayed. Check the following:

Any ideas?

答:
Seems that you want to use LaunchImage Assets for your LaunchScreen. You are setting Source & LaunchScreen, both, at the same time.

If you want to use LaunchImage Assets, Delete the content inside the Launch Screen in info.plist as below:

Launch Screen uses the LaunchScreen.storyboard single file to use across the devices (iPhone/iPads).
While Assets Source uses the Image catalogs, to set specific Launch Image for some specific device of resolution.

You have to use both of this options as an alternatives.


问:
CSS absolute position, z-index
This must be really simple but I'm stuck.

I have a header and below I have a full height/width block that is absolutely positioned. This will be a map but I have just used a coloured block to make it simple.

On top of this background I need the page that is 100% height in the middle. I thought I could use the z-index to show this on top of the absolutely positioned background but the page is always behind the 'bg' div

I know I'm missing something simple

*{
  margin: 0;
  padding: 0;
}

html, body{
  height: 100%;
}

.header{
  background: black;
  height: 50px;
  width: 100%;
}

.bg{
  background: red;
  position: absolute;
  top: 50px;
  bottom: 0;
  left: 0;
  right: 0;
}

.page{
  background: grey;
  height: 100%;
  margin: 0 auto;
  width: 500px;
  z-index: 10;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="header"></div>

<div class="bg"></div>

<div class="page"></div></code>```

答:
To force an absolute positioned element for indexing you could use it in negative.

*{
  margin: 0;
  padding: 0;
}

html, body{
  height: 100%;
}

.header{
  background: black;
  height: 50px;
  width: 100%;
}

.bg{
  background: red;
  position: absolute;
  top: 50px;
  bottom: 0;
  left: 0;
  right: 0;
  z-index: -1;
}

.page{
  background: grey;
  height: 100%;
  margin: 0 auto;
  width: 500px;
  z-index: 10;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="header"></div>

<div class="bg"></div>

<div class="page"></div></code>```

Title: CSS absolute position, z-index

Body:
To force an absolute positioned element for indexing you could use it in negative.

*{
  margin: 0;
  padding: 0;
}

html, body{
  height: 100%;
}

.header{
  background: black;
  height: 50px;
  width: 100%;
}

.bg{
  background: red;
  position: absolute;
  top: 50px;
  bottom: 0;
  left: 0;
  right: 0;
  z-index: -1;
}

.page{
  background: grey;
  height: 100%;
  margin: 0 auto;
  width: 500px;
  z-index: 10;
}

<div class="header"></div>

<div class="bg"></div>

<div class="page"></div>


问:
Using preg_match to validate phone number format
I am having issues making a function that validates that a phone number is in this exact format(xxx)xxx-xxxx.

My attempt was to use preg_match to confirm that the number is in the given format, but I'm having issues with the pattern.

```<code>preg_match("/^([0-9]){3}[0-9]{3}-[0-9]{4}$/", $field)
</code>```

I think my issue is that I don't know how to handle parenthesis in preg_match.

Body:
I am having issues making a function that validates that a phone number is in this exact format(xxx)xxx-xxxx.

My attempt was to use preg_match to confirm that the number is in the given format, but I'm having issues with the pattern.

preg_match("/^([0-9]){3}[0-9]{3}-[0-9]{4}$/", $field)

I think my issue is that I don't know how to handle parenthesis in preg_match.

Body:
You can have all this number validation by this code,

<?php
$array = array(
'0 000 (000) 000-0000',
'000 (000) 000-0000',
'0-000-000-000-0000',
'000 (000) 000-0000',
'000-000-000-0000',
'000-00-0-000-0000',
'0000-00-0-000-0000',
'+000-000-000-0000',
'0 (000) 000-0000',
'+0-000-000-0000',
'0-000-000-0000',
'000-000-0000',
'(000) 000-0000',
'000-0000',
'+9981824139',
9981824139,
919981824139,
'+919981824139',
'qwqwqwqwqwqwqw'
);

foreach($array AS $no){
            var_dump( ( preg_match( '/\d?(\s?|-?|\+?|\.?)((\(\d{1,4}\))|(\d{1,3})|\s?)(\s?|-?|\.?)((\(\d{1,3}\))|(\d{1,3})|\s?)(\s?|-?|\.?)((\(\d{1,3}\))|(\d{1,3})|\s?)(\s?|-?|\.?)\d{3}(-|\.|\s)\d{4}/', $no )
            ||
            preg_match('/([0-9]{8,13})/', str_replace(' ', '', $no))
            ||
            ( preg_match('/^\+?\d+$/', $no) && strlen($no) >= 8 && strlen($no) <= 13 ) )
          );
    }

//var_dump (preg_match('/([0-9]{8,12})/', '99818241') );
//var_dump( strlen(9981) );

//var_dump (preg_match('/^\+?\d+$/', '+12345678') );
//var_dump (preg_match('/^\+?\d+$/', '12345678') );

This will Validate your all type of phone number and output would be

bool(true)
bool(true)
bool(true)
bool(true)
bool(true)
bool(true)
bool(true)
bool(true)
bool(true)
bool(true)
bool(true)
bool(true)
bool(true)
bool(true)
bool(true)
bool(true)
bool(true)
bool(true)
bool(false)


问:
How to implemennt OnZoomListener on MapView
I would like to have onZoomListener on my MapView.
The code below is what I have done. It registers if zoom buttons are tapped. Since all new phones now supports pinch to zoom, this is useless. Does anybody have idea how to do real onZoomListener? Thanks.</p>

```<code>   OnZoomListener listener = new OnZoomListener() {
   @Override
   public void onVisibilityChanged(boolean arg0) {
    // TODO Auto-generated method stub

   }
   @Override
   public void onZoom(boolean arg0) {
    Log.d(TAG, "ZOOM CHANGED");
    // TODO Auto-generated method stub

   }
  };

  ZoomButtonsController zoomButton = mapView.getZoomButtonsController();
  zoomButton.setOnZoomListener(listener);
</code>```

答:
I had to subclass MapView and override dispatchDraw

Here is the code:

```<code> int oldZoomLevel=-1;
 @Override
 public void dispatchDraw(Canvas canvas) {
  super.dispatchDraw(canvas);
  if (getZoomLevel() != oldZoomLevel) {
   Log.d(TAG, "ZOOOMED");
   oldZoomLevel = getZoomLevel();
  }
 }
</code>```

This blog helped me a lot: http://pa.rezendi.com/2010/03/responding-to-zooms-and-pans-in.html

Above works great. Is there maybe simpler solution?
I tried to implement onTouchListener on MapView directly but touch event would be detected only once if onTouchListener would return false. If it would return true, touch would be detected every time, but map zooming and panning wouldn't work.

Body:
I would like to have onZoomListener on my MapView.
The code below is what I have done. It registers if zoom buttons are tapped. Since all new phones now supports pinch to zoom, this is useless. Does anybody have idea how to do real onZoomListener? Thanks.

   OnZoomListener listener = new OnZoomListener() {
   @Override
   public void onVisibilityChanged(boolean arg0) {
    // TODO Auto-generated method stub

   }
   @Override
   public void onZoom(boolean arg0) {
    Log.d(TAG, "ZOOM CHANGED");
    // TODO Auto-generated method stub

   }
  };

  ZoomButtonsController zoomButton = mapView.getZoomButtonsController();
  zoomButton.setOnZoomListener(listener);

Body:
I had to subclass MapView and override dispatchDraw

Here is the code:

 int oldZoomLevel=-1;
 @Override
 public void dispatchDraw(Canvas canvas) {
  super.dispatchDraw(canvas);
  if (getZoomLevel() != oldZoomLevel) {
   Log.d(TAG, "ZOOOMED");
   oldZoomLevel = getZoomLevel();
  }
 }

This blog helped me a lot: http://pa.rezendi.com/2010/03/responding-to-zooms-and-pans-in.html

Above works great. Is there maybe simpler solution?
I tried to implement onTouchListener on MapView directly but touch event would be detected only once if onTouchListener would return false. If it would return true, touch would be detected every time, but map zooming and panning wouldn't work.


问:
ionic 2 innerHTML missing attribute id
I have a script like this...

ts:

```<code>export class namaClass{

 content: any;

 constructor(public navCtrl: NavController, public navParams: NavParams) {

  this.content = [

   {judul: "Judul 1", isi:"<div id='title_1'>Isinya</div>"},

   {judul: "Judul 2", isi:"<div id='title_2'>Isinya</div>"},

  ]

 }

}
</code>```

html:

```<code><div *ngFor="let item of content">
 <h3 [innerHTML]="item.judul"></h3>
 <div [innerHTML]="item.isi"></div>
</div>
</code>```

when I try to DOM/inspect element, element id in [innerHTML]="item.isi" not show. How to show that id?

答:
Here it is :

Component side :

```<code>import { DomSanitizer } from '@angular/platform-browser';

constructor(protected _sanitizer: DomSanitizer) {}

safeHtml(html) {
  return this._sanitizer.bypassSecurityTrustHtml(html);
}
</code>```

Template side :

```<code><div *ngFor="let item of content">
 <h3 [innerHTML]="safeHtml(item.judul)"></h3>
 <div [innerHTML]="safeHtml(item.isi)"></div>
</div>
</code>```

Link to : WORKING DEMO

For more detail : https://angular.io/guide/security

Title: ionic 2 innerHTML missing attribute id

Body:
I have a script like this...

ts:

export class namaClass{

 content: any;

 constructor(public navCtrl: NavController, public navParams: NavParams) {

  this.content = [

   {judul: "Judul 1", isi:"
Isinya
"},

   {judul: "Judul 2", isi:"
Isinya
"},

  ]

 }

}

html:

when I try to DOM/inspect element, element id in [innerHTML]="item.isi" not show. How to show that id?

Body:
Here it is :

Component side :

import { DomSanitizer } from '@angular/platform-browser';

constructor(protected _sanitizer: DomSanitizer) {}

safeHtml(html) {
  return this._sanitizer.bypassSecurityTrustHtml(html);
}

Template side :

<div *ngFor="let item of content">
 <h3 [innerHTML]="safeHtml(item.judul)"></h3>
 <div [innerHTML]="safeHtml(item.isi)"></div>
</div>

Link to : WORKING DEMO

For more detail : https://angular.io/guide/security


问:
route redirects to nothing react-router 4
I'm not sure why everything is redirecting to a blank page:

I'm using:

```<code>"react-router": "^4.2.0",
"react-router-dom": "^4.1.1",
</code>```

App.js

```<code>import { BrowserRouter, Route, Switch } from 'react-router-dom';

    class Container extends Component{
      render() {
        return (
          <div>{this.props.children}</div>
        );
      }
    }

    export default class App extends Component {
      render() {
        return (
          <BrowserRouter onUpdate={onUpdate}>
            <Switch>
              <Route component={HomePageContainer} exact path="/" />
              <Route component={CompanyDetailContainer} name="companydetail" path="interviews/companies/:companyId/details" />
              <Route component={InterviewContainer} name="interview" path="interviews/companies/:companyId" />
              <Route component={Container} path="/" />
              <Route component={NotFound} path="*" />
            </Switch>
          </BrowserRouter>
        );
      }
    }
</code>```

Homepage route to '/' is working fine.

What's not working are all the other routes.

For example when a user clicks a hyperlink that redirects to these routes or other routes other than the default route, I'm getting a blank page:

```<code>   <Route component={CompanyDetailContainer} name="companydetail" path="interviews/companies/:companyId/details" />
      <Route component={InterviewContainer} name="interview" path="interviews/companies/:companyId" />
</code>```

Here is how my routes were working when I was using react-router v3:

```<code><Router history={browserHistory} onUpdate={onUpdate}>
    <Route path="/">
      <IndexRoute component={HomePageContainer} />
      <Route component={InterviewContainer} name="interview"  path="interviews/companies/:companyId" />
      <Route component={About} name="about" path="about"  />
      <Route component={JobList} name="jobs" path="jobs"  />
    </Route>
    <Route component={Container} path="/"  />
    <Route component={NotFound} path="*"  />
</Router>
</code>```

Note that I also added the new route for companydetail just recently.

答:
Try wrapping your router in an anonymous function.</p>

```<code>const App = () => (
      <BrowserRouter onUpdate={onUpdate}>
        <Switch>
          <Route component={HomePageContainer} exact path="/" />
          <Route component={CompanyDetailContainer} name="companydetail" path="interviews/companies/:companyId/details" />
          <Route component={InterviewContainer} name="interview" path="interviews/companies/:companyId" />
          <Route component={Container} path="/" />
          <Route component={NotFound} path="*" />
        </Switch>
      </BrowserRouter>
)
</code>```

Body:
I'm not sure why everything is redirecting to a blank page:

I'm using:

"react-router": "^4.2.0",
"react-router-dom": "^4.1.1",

App.js

import { BrowserRouter, Route, Switch } from 'react-router-dom';

    class Container extends Component{
      render() {
        return (

{this.props.children}

        );
      }
    }

    export default class App extends Component {
      render() {
        return (
          <BrowserRouter onUpdate={onUpdate}>
            <Switch>
              <Route component={HomePageContainer} exact path="/" />
              <Route component={CompanyDetailContainer} name="companydetail" path="interviews/companies/:companyId/details" />
              <Route component={InterviewContainer} name="interview" path="interviews/companies/:companyId" />
              <Route component={Container} path="/" />
              <Route component={NotFound} path="*" />
            </Switch>
          </BrowserRouter>
        );
      }
    }

Homepage route to '/' is working fine.

What's not working are all the other routes.

For example when a user clicks a hyperlink that redirects to these routes or other routes other than the default route, I'm getting a blank page:

   <Route component={CompanyDetailContainer} name="companydetail" path="interviews/companies/:companyId/details" />
      <Route component={InterviewContainer} name="interview" path="interviews/companies/:companyId" />

Here is how my routes were working when I was using react-router v3:

<Router history={browserHistory} onUpdate={onUpdate}>
    <Route path="/">
      <IndexRoute component={HomePageContainer} />
      <Route component={InterviewContainer} name="interview"  path="interviews/companies/:companyId" />
      <Route component={About} name="about" path="about"  />
      <Route component={JobList} name="jobs" path="jobs"  />
    </Route>
    <Route component={Container} path="/"  />
    <Route component={NotFound} path="*"  />
</Router>

Note that I also added the new route for companydetail just recently.

Body:
Try wrapping your router in an anonymous function.

const App = () => (
      <BrowserRouter onUpdate={onUpdate}>
        <Switch>
          <Route component={HomePageContainer} exact path="/" />
          <Route component={CompanyDetailContainer} name="companydetail" path="interviews/companies/:companyId/details" />
          <Route component={InterviewContainer} name="interview" path="interviews/companies/:companyId" />
          <Route component={Container} path="/" />
          <Route component={NotFound} path="*" />
        </Switch>
      </BrowserRouter>
)


问:
div with onclick inside another div click also firing
I have parent div and inside child div's(many). Parent div had addEventListener with click event. But when i click the inside the child div that one also event firing. I want to stop those things.

Example I have A parent div, and B child div.
When i click A div only need to add some logic(get content in b div), when i click the B div don't do anything.

var content= document.querySelector('.test-content');
    content.addEventListener('click', function(evt) {
      var check = this.querySelector('.testClass');
      alert("fired");
      evt = evt || window.event;
      stopPropagation(evt);
    });

 function stopPropagation(evt) {
    if (typeof evt.stopPropagation == "function") {
        evt.stopPropagation();
    } else {
        evt.cancelBubble = true;
    }
  }```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="test-content" style="width:100%;height:200px;background-color:yellow" >This is Div A
<div style="width:20%;height:100px;background-color:red"> This is Div B
 <div class="testClass" > test</div>
</div>
</div></code>```

答:
Simply check if evt.target != this before proceeding further.

Demo

var content= document.querySelector('.test-content');
    content.addEventListener('click', function(evt) {
      if ( evt.target != this ) return false; //notice this line
      alert("fired");
      evt = evt || window.event;
      stopPropagation(evt);
    });

 function stopPropagation(evt) {
    if (typeof evt.stopPropagation == "function") {
        evt.stopPropagation();
    } else {
        evt.cancelBubble = true;
    }
  }```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="test-content" style="width:100%;height:200px;background-color:yellow" >This is Div A
<div style="width:20%;height:100px;background-color:red"> This is Div B</div>
</div></code>```

Body:
I have parent div and inside child div's(many). Parent div had addEventListener with click event. But when i click the inside the child div that one also event firing. I want to stop those things.

Example I have A parent div, and B child div.
When i click A div only need to add some logic(get content in b div), when i click the B div don't do anything.

var content= document.querySelector('.test-content');
    content.addEventListener('click', function(evt) {
      var check = this.querySelector('.testClass');
      alert("fired");
      evt = evt || window.event;
      stopPropagation(evt);
    });

 function stopPropagation(evt) {
    if (typeof evt.stopPropagation == "function") {
        evt.stopPropagation();
    } else {
        evt.cancelBubble = true;
    }
  }

This is Div A

 This is Div B

 test

Body:
Simply check if evt.target != this before proceeding further.

Demo

var content= document.querySelector('.test-content');
    content.addEventListener('click', function(evt) {
      if ( evt.target != this ) return false; //notice this line
      alert("fired");
      evt = evt || window.event;
      stopPropagation(evt);
    });

 function stopPropagation(evt) {
    if (typeof evt.stopPropagation == "function") {
        evt.stopPropagation();
    } else {
        evt.cancelBubble = true;
    }
  }

<div class="test-content" style="width:100%;height:200px;background-color:yellow" >This is Div A
<div style="width:20%;height:100px;background-color:red"> This is Div B</div>
</div>


问:
Gemfire region persistent issue
Currently I'm facing this issue after implementing SecurityManager. A simple gist of what I did was, create an object with populated values if an user logins. If another user logins,  I would overwrite one specific variable in the previous user's object. Then I proceed to stop server and starts it again. When I check through pulse, my two objects are there as expected but that one specific variable reverted to its initial value before the second user logins. It's the same for subsequent users. Any helps are appreciated. </p>

答: Requires region.put(retrieved object's key, the retrieved object) back instead of just object.setVariable().</p>

Title: Gemfire region persistent issue


问:
IntelliJ don't recognize Promise type in a basic Ionic2 project
I am developing an Ionic 2 rc.1 app and I use idea intelliJ 2016.2.4.

Project runs fine but the IDE don't recognize the typescript definition of Promise because it seems the type "is not included in tsconfig.json'

The inspection error is:   Corresponding file is not included in tsconfig.json

my tsconfig.json look like that:

```<code>{
    "compilerOptions": {
    "allowSyntheticDefaultImports": true,
    "declaration": true,
    "emitDecoratorMetadata": true,
    "experimentalDecorators": true,
    "lib": [
      "dom",
      "es2015"
    ],
    "module": "es2015",
    "moduleResolution": "node",
    "target": "es5"
  },
  "exclude": [
    "node_modules"
  ],
  "compileOnSave": false,
  "atom": {
    "rewriteTsconfig": false
  }
}
</code>```

if I remove node_modules from the "exclude" block then I do not have problem with the IDE inspection but the project run ionic serve fails in the lint phase.

here is my package.json

```<code>{
  "name": "ionic-hello-world",
  "author": "Ionic Framework",
  "homepage": "http://ionicframework.com/",
  "private": true,
  "scripts": {
    "build": "ionic-app-scripts build",
    "watch": "ionic-app-scripts watch",
    "serve:before": "watch",
    "emulate:before": "build",
    "deploy:before": "build",
    "build:before": "build",
    "run:before": "build"
  },
  "dependencies": {
    "@angular/common": "^2.0.0",
    "@angular/compiler": "^2.0.0",
    "@angular/compiler-cli": "0.6.2",
    "@angular/core": "^2.0.0",
    "@angular/forms": "^2.0.0",
    "@angular/http": "^2.0.0",
    "@angular/platform-browser": "^2.0.0",
    "@angular/platform-browser-dynamic": "^2.0.0",
    "@angular/platform-server": "^2.0.0",
    "@ionic/storage": "^1.0.3",
    "ionic-angular": "^2.0.0-rc.1",
    "ionic-native": "^2.2.3",
    "ionicons": "^3.0.0",
    "rxjs": "5.0.0-beta.12",
    "zone.js": "^0.6.21"
  },
  "devDependencies": {
    "@ionic/app-scripts": "^0.0.36",
    "typescript": "^2.0.3"
  },
  "cordovaPlugins": [
    "cordova-plugin-device",
    "cordova-plugin-console",
    "cordova-plugin-whitelist",
    "cordova-plugin-splashscreen",
    "cordova-plugin-statusbar",
    "ionic-plugin-keyboard"
  ],
  "cordovaPlatforms": [
    "ios@4.2.1",
    "android@5.2.2"
  ]
}
</code>```

Someone knows how to solve this problem?

Thanks

答: I resolved this by installing typescript globally at the version of typescript in the project</p>

Body:
I am developing an Ionic 2 rc.1 app and I use idea intelliJ 2016.2.4.

Project runs fine but the IDE don't recognize the typescript definition of Promise because it seems the type "is not included in tsconfig.json'

The inspection error is:   Corresponding file is not included in tsconfig.json

my tsconfig.json look like that:

{
    "compilerOptions": {
    "allowSyntheticDefaultImports": true,
    "declaration": true,
    "emitDecoratorMetadata": true,
    "experimentalDecorators": true,
    "lib": [
      "dom",
      "es2015"
    ],
    "module": "es2015",
    "moduleResolution": "node",
    "target": "es5"
  },
  "exclude": [
    "node_modules"
  ],
  "compileOnSave": false,
  "atom": {
    "rewriteTsconfig": false
  }
}

if I remove node_modules from the "exclude" block then I do not have problem with the IDE inspection but the project run ionic serve fails in the lint phase.

here is my package.json

{
  "name": "ionic-hello-world",
  "author": "Ionic Framework",
  "homepage": "http://ionicframework.com/",
  "private": true,
  "scripts": {
    "build": "ionic-app-scripts build",
    "watch": "ionic-app-scripts watch",
    "serve:before": "watch",
    "emulate:before": "build",
    "deploy:before": "build",
    "build:before": "build",
    "run:before": "build"
  },
  "dependencies": {
    "@angular/common": "^2.0.0",
    "@angular/compiler": "^2.0.0",
    "@angular/compiler-cli": "0.6.2",
    "@angular/core": "^2.0.0",
    "@angular/forms": "^2.0.0",
    "@angular/http": "^2.0.0",
    "@angular/platform-browser": "^2.0.0",
    "@angular/platform-browser-dynamic": "^2.0.0",
    "@angular/platform-server": "^2.0.0",
    "@ionic/storage": "^1.0.3",
    "ionic-angular": "^2.0.0-rc.1",
    "ionic-native": "^2.2.3",
    "ionicons": "^3.0.0",
    "rxjs": "5.0.0-beta.12",
    "zone.js": "^0.6.21"
  },
  "devDependencies": {
    "@ionic/app-scripts": "^0.0.36",
    "typescript": "^2.0.3"
  },
  "cordovaPlugins": [
    "cordova-plugin-device",
    "cordova-plugin-console",
    "cordova-plugin-whitelist",
    "cordova-plugin-splashscreen",
    "cordova-plugin-statusbar",
    "ionic-plugin-keyboard"
  ],
  "cordovaPlatforms": [
    "ios@4.2.1",
    "android@5.2.2"
  ]
}

Someone knows how to solve this problem?

Thanks


Title: Multiply the values for each row in two different dataframes

Body:
I'm building genetic algorithm to feature selection in python. I have extracted features from my datas, then I divided into two dataframe, 'train' and 'test' dataframe.
How can I multiple the values for each row in 'population' dataframe (each individu) and 'train' dataframe?

'train' dataframe:

   feature0   feature1   feature2   feature3   feature4   feature5
0  18.279579  -3.921346  13.611829  -7.250185 -11.773605 -18.265003
1  17.899545 -15.503942  -0.741729  -0.053619  -6.734652   4.398419
4  16.432750 -22.490190  -4.611659 -15.247781 -13.941488  -2.433374
5  15.905368  -4.812785  18.291712   3.742221   3.631887  -1.074326
6  16.991823 -15.946251   8.299577   8.057511   8.057510  -1.482333

'population' dataframe:

      0     1     2     3     4     5
0     1     1     0     0     0     1
1     0     1     0     1     0     0
2     0     0     0     0     0     1
3     0     0     1     0     1     1

Multiplying each row in 'population' to all rows in 'train'.
It will results:

1) From population row 1:

   feature0   feature1   feature2   feature3   feature4   feature5
0  18.279579  -3.921346          0          0          0 -18.265003
1  17.899545 -15.503942          0          0          0   4.398419
4  16.432750 -22.490190          0          0          0  -2.433374
5  15.905368  -4.812785          0          0          0  -1.074326
6  16.991823 -15.946251          0          0          0  -1.482333

2) From population row 2:

   feature0   feature1   feature2   feature3   feature4   feature5
0          0  -3.921346          0  -7.250185          0          0
1          0 -15.503942          0  -0.053619          0          0
4          0 -22.490190          0 -15.247781          0          0
5          0  -4.812785          0   3.742221          0          0
6          0 -15.946251          0   8.057511          0          0

And so on...

Body:
I'd use numpy broadcasting to do it all in one go...

train_ = pd.DataFrame(
    (train.values * pop.values[:, None]).reshape(-1, train.shape[1]),
    pd.MultiIndex.from_product([pop.index, train.index]),
    train.columns
)

train_

      feature0   feature1   feature2   feature3   feature4   feature5
0 0  18.279579  -3.921346   0.000000  -0.000000  -0.000000 -18.265003
  1  17.899545 -15.503942  -0.000000  -0.000000  -0.000000   4.398419
  4  16.432750 -22.490190  -0.000000  -0.000000  -0.000000  -2.433374
  5  15.905368  -4.812785   0.000000   0.000000   0.000000  -1.074326
  6  16.991823 -15.946251   0.000000   0.000000   0.000000  -1.482333
1 0   0.000000  -3.921346   0.000000  -7.250185  -0.000000  -0.000000
  1   0.000000 -15.503942  -0.000000  -0.053619  -0.000000   0.000000
  4   0.000000 -22.490190  -0.000000 -15.247781  -0.000000  -0.000000
  5   0.000000  -4.812785   0.000000   3.742221   0.000000  -0.000000
  6   0.000000 -15.946251   0.000000   8.057511   0.000000  -0.000000
2 0   0.000000  -0.000000   0.000000  -0.000000  -0.000000 -18.265003
  1   0.000000  -0.000000  -0.000000  -0.000000  -0.000000   4.398419
  4   0.000000  -0.000000  -0.000000  -0.000000  -0.000000  -2.433374
  5   0.000000  -0.000000   0.000000   0.000000   0.000000  -1.074326
  6   0.000000  -0.000000   0.000000   0.000000   0.000000  -1.482333
3 0   0.000000  -0.000000  13.611829  -0.000000 -11.773605 -18.265003
  1   0.000000  -0.000000  -0.741729  -0.000000  -6.734652   4.398419
  4   0.000000  -0.000000  -4.611659  -0.000000 -13.941488  -2.433374
  5   0.000000  -0.000000  18.291712   0.000000   3.631887  -1.074326
  6   0.000000  -0.000000   8.299577   0.000000   8.057510  -1.482333

You can access just the one corresponding to the ith row or population with train_.loc[i]

train_.loc[3]

   feature0  feature1   feature2  feature3   feature4   feature5
0       0.0      -0.0  13.611829      -0.0 -11.773605 -18.265003
1       0.0      -0.0  -0.741729      -0.0  -6.734652   4.398419
4       0.0      -0.0  -4.611659      -0.0 -13.941488  -2.433374
5       0.0      -0.0  18.291712       0.0   3.631887  -1.074326
6       0.0      -0.0   8.299577       0.0   8.057510  -1.482333

ROUGH TIME TEST

I'm too lazy to do more robust testing

%%timeit
pd.DataFrame(
    (train.values * pop.values[:, None]).reshape(-1, train.shape[1]),
    pd.MultiIndex.from_product([pop.index, train.index]),
    train.columns
)

%%timeit
res = pop.iloc[np.repeat(np.arange(len(pop)), len(train))]
res = res.set_index(np.tile(train.index, len(pop)), append=True).add_prefix('feature')
res.mul(train, level=1)

%%timeit
pd.concat([train * pop.values[i] for i in range(pop.shape[0])],
               keys=pop.index.tolist())

571 µs ± 10.8 µs per loop (mean ± std. dev. of 7 runs, 1000 loops each)
1.42 ms ± 18 µs per loop (mean ± std. dev. of 7 runs, 1000 loops each)
1.7 ms ± 69.5 µs per loop (mean ± std. dev. of 7 runs, 1000 loops each)


问:
different result 22/7 on python 2.7.12 and 3.6
how to make output 22//7 on python 2.7 become 3.14159 ?i try use float(22/7) but it just give me 3.0. I try use Decimal but it just give me 3, use round(x, 6) only give 3.0 just like float.

答:
Here, int/int will return int only that is what happening here 22/7 gives 3 and you're type casting it to float(3) which is giving 3.0 but if you will perform float/int or int/float then it will result into float so you convert any of them to float as shown following.

replace float(22/7) with float(22)/7


问:
EF code first many to many relation when no relation in DB
Suppose I have two classes model like:

```<code> public class AuthorityUser
{
    public string GUID { get; set; }
    public int UserID { get; set; }
    public ICollection<Authority1> Authorities { get; set; }
    public AuthorityUser()
    {
        Authorities = new HashSet<Authority1>();
    }
}
public partial class Authority1
{
    public virtual int AID
    {
        get;
        set;
    }
    public virtual ICollection<AuthorityUser> AuthorityUsers { get; set; }
    public Authority1()
    {
        AuthorityUsers = new HashSet<AuthorityUser>();
    }
}
</code>```

I am going to make Many To Many relation between them based on UserAuthorityMap connected table in DB.

so I did this to make M:N relation in OnModelCreating()

```<code>modelBuilder.Entity<AuthorityUser>().ToTable("Gainer").HasKey(x => x.UserID);
modelBuilder.Entity<Authority1>().ToTable("Authority").HasKey(x => x.AID);
modelBuilder.Entity<AuthorityUser>()
          .HasMany<Authority1>(s => s.Authorities)
          .WithMany(c => c.AuthorityUsers)
          .Map(cs =>
          {
              cs.MapLeftKey("UserID");
              cs.MapRightKey("AID");
              cs.ToTable("UserAuthorityMap");
          });
</code>```

As I mentioned in title there is no relation between them in DB so the diagram in DB is like picture below :

when I run this :

```<code>dbContext.AuthorityUsers.SingleOrDefault(x => x.UserID == 65);
</code>```

the related Authorities won't be loaded from DB.

so should I use HasDatabaseGeneratedOption(DatabaseGeneratedOption.None) to make it right or something else?

答:
Since Authorities navigation property is not virtual,  lazy loading has been turned off and thus you have 2 options left to load them.

Option 1: Eager Loading

```<code>dbContext.AuthorityUsers.Include(x => x.Authorities).SingleOrDefault(x => x.UserID == 65);
</code>```

Note: Include is an extension method in the System.Data.Entity namespace so make sure you are using that namespace.

Option 2: Explicit Loading

```<code>var users = dbContext.AuthorityUsers.SingleOrDefault(x => x.UserID == 65);
dbContext.Entry(users).Collection(p => p.Authorities).Load();
</code>```

Please see this article for more details.

Body:
Suppose I have two classes model like:

 public class AuthorityUser
{
    public string GUID { get; set; }
    public int UserID { get; set; }
    public ICollection<Authority1> Authorities { get; set; }
    public AuthorityUser()
    {
        Authorities = new HashSet<Authority1>();
    }
}
public partial class Authority1
{
    public virtual int AID
    {
        get;
        set;
    }
    public virtual ICollection<AuthorityUser> AuthorityUsers { get; set; }
    public Authority1()
    {
        AuthorityUsers = new HashSet<AuthorityUser>();
    }
}

I am going to make Many To Many relation between them based on UserAuthorityMap connected table in DB.

so I did this to make M:N relation in OnModelCreating()

modelBuilder.Entity<AuthorityUser>().ToTable("Gainer").HasKey(x => x.UserID);
modelBuilder.Entity<Authority1>().ToTable("Authority").HasKey(x => x.AID);
modelBuilder.Entity<AuthorityUser>()
          .HasMany<Authority1>(s => s.Authorities)
          .WithMany(c => c.AuthorityUsers)
          .Map(cs =>
          {
              cs.MapLeftKey("UserID");
              cs.MapRightKey("AID");
              cs.ToTable("UserAuthorityMap");
          });

As I mentioned in title there is no relation between them in DB so the diagram in DB is like picture below :

when I run this :

dbContext.AuthorityUsers.SingleOrDefault(x => x.UserID == 65);

the related Authorities won't be loaded from DB.

so should I use HasDatabaseGeneratedOption(DatabaseGeneratedOption.None) to make it right or something else?

Body:
Since Authorities navigation property is not virtual,  lazy loading has been turned off and thus you have 2 options left to load them.

Option 1: Eager Loading

dbContext.AuthorityUsers.Include(x => x.Authorities).SingleOrDefault(x => x.UserID == 65);

Note: Include is an extension method in the System.Data.Entity namespace so make sure you are using that namespace.

Option 2: Explicit Loading

var users = dbContext.AuthorityUsers.SingleOrDefault(x => x.UserID == 65);
dbContext.Entry(users).Collection(p => p.Authorities).Load();

Please see this article for more details.


问:
Convert the UTC datetime to any other time zone dynamically in php
I want to convert the UTC datetime to any other time zone.its working fine.
But it showing only for one time zone,so to view the other time zone need to change the code every time.
i want to  convert the UTC datetime to any other time zone dynamically.may be by selecting drop down or some other way.

    <?php
$date = new DateTime('2017-11-15 01:00:00 +00');
$date->setTimezone(new DateTimeZone('Asia/Calcutta'));
echo $date->format('Y-m-d H:i:s');
?>```

答:
You can timezone by this code where you can change the $timezone variable value from your dropdown.

```<code>$timezone=  'Asia/Calcutta';
$date = new DateTime('2017-11-15 01:00:00 +00');
$date = new DateTime($date, new DateTimeZone($timezone));
echo $date->format('Y-m-d H:i:s');
</code>```

Body:
You can timezone by this code where you can change the $timezone variable value from your dropdown.

$timezone=  'Asia/Calcutta';
$date = new DateTime('2017-11-15 01:00:00 +00');
$date = new DateTime($date, new DateTimeZone($timezone));
echo $date->format('Y-m-d H:i:s');


问:
Why can't you UnRegisterStartupScript?
Seems to me it is a bit wierd that you can do..

```<code>Page.ClientScript.RegisterStartupScript(this.GetType(), "KeyName", "alert('changed my mind')", true);
</code>```

And then later on you can't unregister or stop the javascript from being rendered programatically.

Why would Microsoft do this?

I don't like the work around here..
http://hemant-vikram.blogspot.com/2005/11/unregister-startup-script-workaround.html

And I don't like the option of just re-registering it and having it do nothing..

Thoughts?

答:
How do I overwrite a Javascript function added (dynamically) by Asp.Net UpdatePanel?

I think an using updatepanel is one of solution to overwrite js. When we use update panel a JavaScript is not run on partial post back and must be registered by code:

```<code>    var prm = Sys.WebForms.PageRequestManager.getInstance();
    prm.add_endRequest(someFunciton);
</code>```

If we do not this then we can register/render a modified function again on partial post back in update panel. In such case are some problem with scope of function.

Sorry for my English.

Title: Why can't you UnRegisterStartupScript?

Body:
Seems to me it is a bit wierd that you can do..

Page.ClientScript.RegisterStartupScript(this.GetType(), "KeyName", "alert('changed my mind')", true);

And then later on you can't unregister or stop the javascript from being rendered programatically.

Why would Microsoft do this?

I don't like the work around here..
http://hemant-vikram.blogspot.com/2005/11/unregister-startup-script-workaround.html

And I don't like the option of just re-registering it and having it do nothing..

Thoughts?

Body:
How do I overwrite a Javascript function added (dynamically) by Asp.Net UpdatePanel?

I think an using updatepanel is one of solution to overwrite js. When we use update panel a JavaScript is not run on partial post back and must be registered by code:

    var prm = Sys.WebForms.PageRequestManager.getInstance();
    prm.add_endRequest(someFunciton);

If we do not this then we can register/render a modified function again on partial post back in update panel. In such case are some problem with scope of function.

Sorry for my English.


问:
Regular Expression (regex) to Parse HTML Segment
I am currently trying to come up with a regular expression that will parse out something like the following:

ORIGINAL HTML:

```<code><td align="center"><p>line 1</p><p>line 2</p><p>line 3</p></td>
</code>```

INTENDED HTML:

```<code><td align="center">line 1<br />line 2<br />line 3</td>
</code>```

Note that there are other
...
 tags throughout the HTML document that must not be touched. I only want to replace
...
 within a  or  only.

I would also need a regexp to reverse the process. Please note that these regular expressions have to work in VB/VBScript/Classic ASP, so although I can use lookaheads (which I think is the key here), I cannot use lookbehinds. Some regex's I've tried unsuccessfully are:

```<code>1. <td[^>]*>(<p>.+<\/p>)<\/td>
2. <td[^>]*>(<p>.+<\/p>)+?<\/td>
3. <td[^>]*><p>(?:(.+?)<\/p><p>(.+))+<\/p><\/td>
4. <td[^>]*>(<p>(?:(?!<\/p>)).*<\/p>)+?<\/td>
5. <td[^>]*>(?:<p>(.+?)<\/p>)*(?:<p>(.+)<\/p>)<\/td>
6. <td[^>]*>(?:<p>(.+?)<\/p>)(?:<p>(.+)<\/p>)*(?:<p>(.+)<\/p>)<\/td>
</code>```

I can "cheat" and pull out the entire line and then parse it manually usually standard VB string manipulation functions, but that's definitely not the most elegant, nor the fastest way. There has to be some way to do this in one shot using RegEx's.

Eventually I'd like to take...

```<code><td align="center"><p><span style="color:#ff0000;"><strong>line 1</strong></span></p><p>line 2</p><p>line 3</p></td>
</code>```

...and turn it into

```<code><td align="center"><span style="color:#ff0000;"><strong>line 1</strong></span><br />line 2<br />line 3</td>
</code>```

Any ideas (besides not to do this with a regex, lol)?

Thank you!

答:
Here's your problem:

There has to be some way to do this in one shot using RegEx's.

This is false, there is no way. It's mathematically impossible. Regular expressions, even ones with lookahead, cannot maintain state required to parse an HTML expression.

You have to use an HTML parser. Many have been written, if you specify your target environment we can help you select one. For example, in .Net the HTML Agility Pack is good.

Body:
I am currently trying to come up with a regular expression that will parse out something like the following:

ORIGINAL HTML:

line 1

line 2

line 3

INTENDED HTML:

line 1
line 2
line 3

Note that there are other
...
 tags throughout the HTML document that must not be touched. I only want to replace
...
 within a  or  only.

I would also need a regexp to reverse the process. Please note that these regular expressions have to work in VB/VBScript/Classic ASP, so although I can use lookaheads (which I think is the key here), I cannot use lookbehinds. Some regex's I've tried unsuccessfully are:

1. ]*>(
.+<\/p>)<\/td>
2. ]*>(
.+<\/p>)+?<\/td>
3. ]*>
(?:(.+?)<\/p>
(.+))+<\/p><\/td>
4. ]*>(
(?:(?!<\/p>)).*<\/p>)+?<\/td>
5. ]*>(?:
(.+?)<\/p>)*(?:
(.+)<\/p>)<\/td>
6. ]*>(?:
(.+?)<\/p>)(?:
(.+)<\/p>)*(?:
(.+)<\/p>)<\/td>

I can "cheat" and pull out the entire line and then parse it manually usually standard VB string manipulation functions, but that's definitely not the most elegant, nor the fastest way. There has to be some way to do this in one shot using RegEx's.

Eventually I'd like to take...

line 1

line 2

line 3

...and turn it into

line 1
line 2
line 3

Any ideas (besides not to do this with a regex, lol)?

Thank you!


问:
Type mismatch: cannot convert from double to int
Need to write a program to calculate sum of all digits and then give results when the total sum vaue ends with 5 or 8.Please help correct this code!</p>

```<code>import java.util.Scanner;
public class Main {

    public static void main(String[] args) {

        Scanner in= new Scanner(System.in);
        int customerID = in.nextInt();
        while(customerID > 0)
        {
        int Reminder = customerID % 10;
        int sum = sum+ Reminder;
        customerID = customerID / 10;
        }
        if(sum%5||sum%8)
        {
        System.out.println("Lucky Customer");
        }else
        {
        System.out.println("Unlucky Customer");
        }
        if(sum <0)
        {
        System.out.println("Invalid Input");
        }
        }
        }
</code>```

答:
instead of doing

```<code>if(sum%5||sum%8)
    {
    System.out.println("Lucky Customer");
    }
</code>```

where sum%8 will be true for the value 16 so you can try this

```<code>int rem=sum%10;
if(rem==5||rem==8)
{
      System.out.println("Lucky Customer");
}
</code>```

Body:
Need to write a program to calculate sum of all digits and then give results when the total sum vaue ends with 5 or 8.Please help correct this code!

import java.util.Scanner;
public class Main {

    public static void main(String[] args) {

        Scanner in= new Scanner(System.in);
        int customerID = in.nextInt();
        while(customerID > 0)
        {
        int Reminder = customerID % 10;
        int sum = sum+ Reminder;
        customerID = customerID / 10;
        }
        if(sum%5||sum%8)
        {
        System.out.println("Lucky Customer");
        }else
        {
        System.out.println("Unlucky Customer");
        }
        if(sum <0)
        {
        System.out.println("Invalid Input");
        }
        }
        }

Body:
instead of doing

if(sum%5||sum%8)
    {
    System.out.println("Lucky Customer");
    }

where sum%8 will be true for the value 16 so you can try this

int rem=sum%10;
if(rem==5||rem==8)
{
      System.out.println("Lucky Customer");
}


问:
Provided an image that is available locally already
I'm using React Native and Firebase in my app. And out of nowhere I just started recieving this error:

```<code>SyntaxError: Unexpected end of JSON input.
at doWrite(_stream_writable.js)
at Promise.resolve.then.then.then.catch.then.message
</code>```

and in my react packager it is pointing to this code:

```<code>    onProfilesChange = async (snap) => {
    var allProfilePromises = []
    snap.forEach((child) => {
      var profileId = child.val().profileId
      var alreadyAdded = this.state.profiles.some(x => x.id === profileId)

      if (alreadyAdded === false) {
        var profilePromise = this.registerOnProfileChanges(profileId)
        allProfilePromises.push(profilePromise)
      }
    })

    await Promise.all(allProfilePromises)

    var profileCount = snap.numChildren()
    this.setState({ profiles: this.state.profiles, loading: false, profileCount: profileCount })

    if (profileCount <= 0) {
      this.getUserName()
    }
  }
</code>```

which is being run when componentMount is called. Now the error is quite clear, but I don't know WHY it is being produced, nor how to get passed it. This code has worked for months without me changing anything to it.

Thank in advance.

答:
I met the same problem. It is relevant to image.

I solved this by changing the version of react-native-img-cache.

run this:

        npm install react-native-img-cache@1.4.0

Body:
I'm using React Native and Firebase in my app. And out of nowhere I just started recieving this error:

SyntaxError: Unexpected end of JSON input.
at doWrite(_stream_writable.js)
at Promise.resolve.then.then.then.catch.then.message

and in my react packager it is pointing to this code:

    onProfilesChange = async (snap) => {
    var allProfilePromises = []
    snap.forEach((child) => {
      var profileId = child.val().profileId
      var alreadyAdded = this.state.profiles.some(x => x.id === profileId)

      if (alreadyAdded === false) {
        var profilePromise = this.registerOnProfileChanges(profileId)
        allProfilePromises.push(profilePromise)
      }
    })

    await Promise.all(allProfilePromises)

    var profileCount = snap.numChildren()
    this.setState({ profiles: this.state.profiles, loading: false, profileCount: profileCount })

    if (profileCount <= 0) {
      this.getUserName()
    }
  }

which is being run when componentMount is called. Now the error is quite clear, but I don't know WHY it is being produced, nor how to get passed it. This code has worked for months without me changing anything to it.

Thank in advance.


问:
Trouble with tables in html and css
I was wondering if you could help me with this problem:
I'm making a table in html and i want to have space between cells but i also need the cell with the heading and the text to be collapsed. So is there a way to just collapse the borders with the th and td tags?

I want to remove the space marked with red

答:
The answer is no; you cannot collapse some borders in a table while keeping others separated. So you should look for other solutions.

One would be omitting the th altogether and putting the all the info in the td, by using a figure with a figcaption.

body {
  background: #c0d0e0;
  margin: 1em
}

table {
  border-spacing: 1em
}

td {
  background:white;
  border: 2px solid black;
  padding: 0
}

figure {
  display: block;
  margin: 0
}

figcaption {
  background: #d1d1d1;
  padding: .333em;
  border-bottom: 2px solid #6e6e6e;
}

figure img {
  display: block;
  margin: 1em;
  border-radius:.667em;
  height:100px;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><table>
  <tr>
    <td>
      <figure>
        <figcaption>caption for image 1</figcaption>
        <img src="http://lorempixel.com/101/100" alt="one" />
      </figure>
    </td>
    <td>
      <figure>
        <figcaption>caption for image 2</figcaption>
        <img src="http://lorempixel.com/102/100" alt="two" />
      </figure>
    </td>
  </tr>
  <tr>
    <td>
      <figure>
        <figcaption>caption for image 3</figcaption>
        <img src="http://lorempixel.com/103/100" alt="three" />
      </figure>
    </td>
    <td>
      <figure>
        <figcaption>caption for image 4</figcaption>
        <img src="http://lorempixel.com/104/100" alt="four" />
      </figure>
    </td>
  </tr>
</table></code>```

Title: Trouble with tables in html and css

Body:
The answer is no; you cannot collapse some borders in a table while keeping others separated. So you should look for other solutions.

One would be omitting the th altogether and putting the all the info in the td, by using a figure with a figcaption.

body {
  background: #c0d0e0;
  margin: 1em
}

table {
  border-spacing: 1em
}

td {
  background:white;
  border: 2px solid black;
  padding: 0
}

figure {
  display: block;
  margin: 0
}

figcaption {
  background: #d1d1d1;
  padding: .333em;
  border-bottom: 2px solid #6e6e6e;
}

figure img {
  display: block;
  margin: 1em;
  border-radius:.667em;
  height:100px;
}

<table>
  <tr>
    <td>
      <figure>
        <figcaption>caption for image 1</figcaption>
        <img src="http://lorempixel.com/101/100" alt="one" />
      </figure>
    </td>
    <td>
      <figure>
        <figcaption>caption for image 2</figcaption>
        <img src="http://lorempixel.com/102/100" alt="two" />
      </figure>
    </td>
  </tr>
  <tr>
    <td>
      <figure>
        <figcaption>caption for image 3</figcaption>
        <img src="http://lorempixel.com/103/100" alt="three" />
      </figure>
    </td>
    <td>
      <figure>
        <figcaption>caption for image 4</figcaption>
        <img src="http://lorempixel.com/104/100" alt="four" />
      </figure>
    </td>
  </tr>
</table>


问:
'git checkout' is not creating local branch to match remote tracking branch
On one machine, calling git checkout will not create a local branch.

For example, if I have a remote tracking branch origin/master, I can call git checkout origin/master, and it will work fine, putting me in a headless state.

But if I try to call git checkout master, I get the error error: pathspec 'master' did not match any file(s) known to git.

I tried this on another machine, and it worked just fine.

They have the exact same version of git installed (2.15.0.windows.1).  git config --list shows one difference.  The machine where it worked properly had the following line in its configuration:

```<code>remote.origin.fetch=+refs/heads/*:refs/remotes/origin/*
</code>```

What would put that in the local configuration, why might it be missing from one of the systems, and what is the proper thing to do to fix the problem?

答:
To answer things sequentially to question,

Q: On one machine, calling git checkout will not create a local branch.

A: No it does not create branch, use git checkout -b 'branch_name' to create local branch

Q: But if I try to call git checkout master, I get the error error: pathspec 'master' did not match any file(s) known to git.

A: That's because you do not have remote references updated in your staging dir.

Run below in sequence

git remote update should sets things up to point to remote origin branches including master

git fetch -- Fetch branches and/or tags (collectively, "refs") from one or more other repositories, along with the objects necessary to complete their histories. Remote-tracking branches are updated (see the description of  below for ways to control this behavior). Ref : https://git-scm.com/docs/git-fetch

git checkout master -- Now will checkout master fetching from origin master & switches to it.

Earlier answer of running from git clone <repo-url> sets things up Or you can follow above to fix problem

Body:
On one machine, calling git checkout will not create a local branch.

For example, if I have a remote tracking branch origin/master, I can call git checkout origin/master, and it will work fine, putting me in a headless state.

But if I try to call git checkout master, I get the error error: pathspec 'master' did not match any file(s) known to git.

I tried this on another machine, and it worked just fine.

They have the exact same version of git installed (2.15.0.windows.1).  git config --list shows one difference.  The machine where it worked properly had the following line in its configuration:

remote.origin.fetch=+refs/heads/*:refs/remotes/origin/*

What would put that in the local configuration, why might it be missing from one of the systems, and what is the proper thing to do to fix the problem?


问:
no pg_hba.conf entry for host
I get following error when I try to connect using DBI

```
DBI connect('database=chaosLRdb;host=192.168.0.1;port=5433','postgres',...)
failed: FATAL:  no pg_hba.conf entry for host "192.168.0.1", user "postgres", database "chaosLRdb", SSL off
```

Here is my pg_hba.conf file:

```<code># "local" is for Unix domain socket connections only
local   all         all                               md5
# IPv4 local connections:
host    all         all         127.0.0.1/32          md5
# IPv6 local connections:
host    all         all         ::1/128               md5

host    all         postgres    127.0.0.1/32          trust

host    all        postgres     192.168.0.1/32        trust

host    all        all         192.168.0.1/32        trust

host    all        all         192.168.0.1/128        trust

host    all        all         192.168.0.1/32        md5

host    chaosLRdb    postgres         192.168.0.1/32      md5
local    all        all         192.168.0.1/32        trust
</code>```

My perl code is

```<code>#!/usr/bin/perl-w
use DBI;
use FileHandle;

print "Start connecting to the DB...\n";

@ary = DBI->available_drivers(true);
%drivers = DBI->installed_drivers();
my $dbh = DBI->connect("DBI:PgPP:database=chaosLRdb;host=192.168.0.1;port=5433", "postgres", "chaos123");
</code>```

May I know what i miss here?

答:
In your pg_hba.conf file, I see some incorrect and confusing lines:

```<code># fine, this allows all dbs, all users, to be trusted from 192.168.0.1/32
# not recommend because of the lax permissions
host    all        all         192.168.0.1/32        trust

# wrong, /128 is an invalid netmask for ipv4, this line should be removed
host    all        all         192.168.0.1/128       trust

# this conflicts with the first line
# it says that that the password should be md5 and not plaintext
# I think the first line should be removed
host    all        all         192.168.0.1/32        md5

# this is fine except is it unnecessary because of the previous line
# which allows any user and any database to connect with md5 password
host    chaosLRdb  postgres    192.168.0.1/32        md5

# wrong, on local lines, an IP cannot be specified
# remove the 4th column
local   all        all         192.168.0.1/32        trust
</code>```

I suspect that if you md5'd the password, this might work if you trim the lines.  To get the md5 you can use perl or the following shell script:

```<code> echo -n 'chaos123' | md5sum
 > d6766c33ba6cf0bb249b37151b068f10  -
</code>```

So then your connect line would like something like:

```<code>my $dbh = DBI->connect("DBI:PgPP:database=chaosLRdb;host=192.168.0.1;port=5433",
    "chaosuser", "d6766c33ba6cf0bb249b37151b068f10");
</code>```

For more information, here's the documentation of postgres 8.X's pg_hba.conf file.

OwnerDisplayName: Priya

Title: no pg_hba.conf entry for host

Body:
I get following error when I try to connect using DBI

DBI connect('database=chaosLRdb;host=192.168.0.1;port=5433','postgres',...)
failed: FATAL:  no pg_hba.conf entry for host "192.168.0.1", user "postgres", database "chaosLRdb", SSL off

Here is my pg_hba.conf file:

# "local" is for Unix domain socket connections only
local   all         all                               md5
# IPv4 local connections:
host    all         all         127.0.0.1/32          md5
# IPv6 local connections:
host    all         all         ::1/128               md5

host    all         postgres    127.0.0.1/32          trust

host    all        postgres     192.168.0.1/32        trust

host    all        all         192.168.0.1/32        trust

host    all        all         192.168.0.1/128        trust

host    all        all         192.168.0.1/32        md5

host    chaosLRdb    postgres         192.168.0.1/32      md5
local    all        all         192.168.0.1/32        trust

My perl code is

#!/usr/bin/perl-w
use DBI;
use FileHandle;

print "Start connecting to the DB...\n";

@ary = DBI->available_drivers(true);
%drivers = DBI->installed_drivers();
my $dbh = DBI->connect("DBI:PgPP:database=chaosLRdb;host=192.168.0.1;port=5433", "postgres", "chaos123");

May I know what i miss here?

Body:
In your pg_hba.conf file, I see some incorrect and confusing lines:

# fine, this allows all dbs, all users, to be trusted from 192.168.0.1/32
# not recommend because of the lax permissions
host    all        all         192.168.0.1/32        trust

# wrong, /128 is an invalid netmask for ipv4, this line should be removed
host    all        all         192.168.0.1/128       trust

# this conflicts with the first line
# it says that that the password should be md5 and not plaintext
# I think the first line should be removed
host    all        all         192.168.0.1/32        md5

# this is fine except is it unnecessary because of the previous line
# which allows any user and any database to connect with md5 password
host    chaosLRdb  postgres    192.168.0.1/32        md5

# wrong, on local lines, an IP cannot be specified
# remove the 4th column
local   all        all         192.168.0.1/32        trust

I suspect that if you md5'd the password, this might work if you trim the lines.  To get the md5 you can use perl or the following shell script:

 echo -n 'chaos123' | md5sum
 > d6766c33ba6cf0bb249b37151b068f10  -

So then your connect line would like something like:

my $dbh = DBI->connect("DBI:PgPP:database=chaosLRdb;host=192.168.0.1;port=5433",
    "chaosuser", "d6766c33ba6cf0bb249b37151b068f10");

For more information, here's the documentation of postgres 8.X's pg_hba.conf file.


问:
Fetch values from nested xml (having : in tag name) in php
I have xml like this

```<code><item>
    <title>test title</title>
    <link>www.test.com</link>
    <pubDate>Sun, 27 Aug 2017 06:22:29 +0000</pubDate>
    <post-id xmlns="com-wordpress:feed-additions:1">1111</post-id>
    <ev:tribe_event_meta xmlns:ev="Event">
        <ev:startdate>November 13, 2017</ev:startdate>
        <ev:enddate>November 14, 2017</ev:enddate>
        <ev:venue>venue</ev:venue>
        <ev:address>address</ev:address>
        <ev:city>city</ev:city>
        <ev:zip></ev:zip>
    </ev:tribe_event_meta>
</item>
</code>```

Form this xml i am able to get title, link etc...

But im not able to get any data inside ev:tribe_event_meta. I need to get the value of ev:startdate, ev:enddate,etc.

Please help.

Thanks in advance.

Note: I'm using Drupal Feed Import.

答: XML is just a text file. If your parser can't parse it like that try just doing search/replace on file before passing the file content to the parser. I.e. replace every "ev:startdate" with "ev_startdate" or something.</p>

Body:
I have xml like this

<item>
    <title>test title</title>
    <link>www.test.com</link>
    <pubDate>Sun, 27 Aug 2017 06:22:29 +0000</pubDate>
    <post-id xmlns="com-wordpress:feed-additions:1">1111</post-id>
    <ev:tribe_event_meta xmlns:ev="Event">
        <ev:startdate>November 13, 2017</ev:startdate>
        <ev:enddate>November 14, 2017</ev:enddate>
        <ev:venue>venue</ev:venue>
        <ev:address>address</ev:address>
        <ev:city>city</ev:city>
        <ev:zip></ev:zip>
    </ev:tribe_event_meta>
</item>

Form this xml i am able to get title, link etc...

But im not able to get any data inside ev:tribe_event_meta. I need to get the value of ev:startdate, ev:enddate,etc.

Please help.

Thanks in advance.

Note: I'm using Drupal Feed Import.


答:
This code throws this exception only if your input would contain a dot (e.g.: "3.0"). So either pass the int value (e.g.: "3") or use scanner.nextDouble() and then convert it to int.

Also look into Yash's answer, because your code has other problems too.

+never write variable names with capital letter ("Reminder")!!!!

Title: Type mismatch: cannot convert from double to int


问:
DDMS - Can't bind to local 8600 for debugger on Android Studio
Am trying to view my database tables using Android Device Monitor and It showing me Errors for reasons which i am not really sure of. And i don't have another instance of DDMS running.

Instead of showing my DDMS, Its showing me this errors

```<code>[2015-09-10 17:39:53 - ddms] Could not open Selected VM debug port (8700). Make sure you do not have another instance of DDMS or of the eclipse plugin running. If it's being used by something else, choose a new port number in the preferences.
[2015-09-10 17:39:53 - ddms] Can't bind to local 8600 for debugger
[2015-09-10 17:39:53 - ddmlib] Broken pipe
java.io.IOException: Broken pipe
    at sun.nio.ch.FileDispatcherImpl.write0(Native Method)
    at sun.nio.ch.SocketDispatcher.write(SocketDispatcher.java:47)
    at sun.nio.ch.IOUtil.writeFromNativeBuffer(IOUtil.java:93)
    at sun.nio.ch.IOUtil.write(IOUtil.java:65)
    at sun.nio.ch.SocketChannelImpl.write(SocketChannelImpl.java:487)
    at com.android.ddmlib.JdwpPacket.writeAndConsume(JdwpPacket.java:213)
    at com.android.ddmlib.Client.sendAndConsume(Client.java:677)
    at com.android.ddmlib.HandleHeap.sendREAQ(HandleHeap.java:349)
    at com.android.ddmlib.Client.requestAllocationStatus(Client.java:523)
    at com.android.ddmlib.DeviceMonitor.createClient(DeviceMonitor.java:847)
    at com.android.ddmlib.DeviceMonitor.openClient(DeviceMonitor.java:815)
    at com.android.ddmlib.DeviceMonitor.processIncomingJdwpData(DeviceMonitor.java:775)
    at com.android.ddmlib.DeviceMonitor.deviceClientMonitorLoop(DeviceMonitor.java:664)
    at com.android.ddmlib.DeviceMonitor.access$100(DeviceMonitor.java:46)
    at com.android.ddmlib.DeviceMonitor$3.run(DeviceMonitor.java:592)
</code>```

Please, any one knows a solution to this ???

答:
On Mac, Open terminal and type:

```<code>    sudo nano /etc/hosts
</code>```

Add following line to your hosts file

```<code>127.0.0.1        localhost
</code>```

Save and exit.

In Android Studio, you can start debugging again. I got stuck with the same problem and I ended up doing above, problem solved.

Hope this helps :) .

Body:
Am trying to view my database tables using Android Device Monitor and It showing me Errors for reasons which i am not really sure of. And i don't have another instance of DDMS running.

Instead of showing my DDMS, Its showing me this errors

[2015-09-10 17:39:53 - ddms] Could not open Selected VM debug port (8700). Make sure you do not have another instance of DDMS or of the eclipse plugin running. If it's being used by something else, choose a new port number in the preferences.
[2015-09-10 17:39:53 - ddms] Can't bind to local 8600 for debugger
[2015-09-10 17:39:53 - ddmlib] Broken pipe
java.io.IOException: Broken pipe
    at sun.nio.ch.FileDispatcherImpl.write0(Native Method)
    at sun.nio.ch.SocketDispatcher.write(SocketDispatcher.java:47)
    at sun.nio.ch.IOUtil.writeFromNativeBuffer(IOUtil.java:93)
    at sun.nio.ch.IOUtil.write(IOUtil.java:65)
    at sun.nio.ch.SocketChannelImpl.write(SocketChannelImpl.java:487)
    at com.android.ddmlib.JdwpPacket.writeAndConsume(JdwpPacket.java:213)
    at com.android.ddmlib.Client.sendAndConsume(Client.java:677)
    at com.android.ddmlib.HandleHeap.sendREAQ(HandleHeap.java:349)
    at com.android.ddmlib.Client.requestAllocationStatus(Client.java:523)
    at com.android.ddmlib.DeviceMonitor.createClient(DeviceMonitor.java:847)
    at com.android.ddmlib.DeviceMonitor.openClient(DeviceMonitor.java:815)
    at com.android.ddmlib.DeviceMonitor.processIncomingJdwpData(DeviceMonitor.java:775)
    at com.android.ddmlib.DeviceMonitor.deviceClientMonitorLoop(DeviceMonitor.java:664)
    at com.android.ddmlib.DeviceMonitor.access$100(DeviceMonitor.java:46)
    at com.android.ddmlib.DeviceMonitor$3.run(DeviceMonitor.java:592)

Please, any one knows a solution to this ???

Body:
On Mac, Open terminal and type:

    sudo nano /etc/hosts

Add following line to your hosts file

127.0.0.1        localhost

Save and exit.

In Android Studio, you can start debugging again. I got stuck with the same problem and I ended up doing above, problem solved.

Hope this helps :) .


问:
Does usage of COSMOS data migration tool consuming any RUs?
Does usage of COSMOS data migration tool for periodical backups (export data to blob storage and then restore it when needed) consuming any RUs ? And does it affect performance or availability of my db operations?
What is recommended solution to implement in COSMOS smth like snapshots for blobs in az storage?</p>

答:
Does usage of COSMOS data migration tool for periodical backups
  (export data to blob storage and then restore it when needed)
  consuming any RUs?

Yes. Because you're reading from your Cosmos DB collections you will consume RUs.

And does it affect performance or availability of my db operations?

Again, Yes. Simply because you have assigned certain RUs for your collection and taking a backup is consuming a part of those RUs effectively leaving you with lesser RUs for other operations.

What is recommended solution to implement in COSMOS smth like
  snapshots for blobs in az storage?

I'm also curious to know about this. Just thinking out loud, one possible solution would be to increase the throughput (i.e. either assign more RUs or enable RUPM) when backup is going on so that other operations are not impacted and bring them back to normal once backup is done.