问:
Excel Total Count
I want total time consumed of below C column for respective tasks placed in column A and column B consisting of corresponding time

答:
Enter the formula in cell F2 , and drag down,

```<code>=SUMIF(A:A,E2,B:B)
</code>```

Format the F column to hh:mm format to get the desired result. You can do this by selecting column F and pressing Ctrl + 1, and select the format.

Formula in cell F5,

```<code>=SUM(F2:F4)
</code>```

Note:- Cell E2 in your image is Meetings which should actually be Meeting, for this formula to work. You cannot have a different word in column E and a different word in column A.

Title: Excel Total Count

Body:
Enter the formula in cell F2 , and drag down,

=SUMIF(A:A,E2,B:B)

Format the F column to hh:mm format to get the desired result. You can do this by selecting column F and pressing Ctrl + 1, and select the format.

Formula in cell F5,

=SUM(F2:F4)

Note:- Cell E2 in your image is Meetings which should actually be Meeting, for this formula to work. You cannot have a different word in column E and a different word in column A.


来源: stackexchange

问:
Not able to add static UITableViewCell into tableview
As I am new in IOS development I am trying to add CustomeCell into tableView but I can not add it from library.

What I am doing is just drag TableView in my ViewController and than drag tableview cell in it but its added as extra view under ViewController 's view not able to add it into tableview.

I am stuck here any idea how can I add cell by drag and drop.

Screen shot :

I know how to add cell by coding but its very lengthy process to add every thing by code.

Any guidence will be appreciated.

Thanks in advance.

答:
I'm sorry for late answer, if you're using xib layout check this;

Cannot add a PrototypeCell to UITableView inside xib file

ContentLicense: CC BY-SA 3.0


问:
Will DateTime.UtcNow return different values within the same method?
Say that I have a long loop of simple math in between two calls to DateTime.UtcNow in a single method.

Does DateTime.UtcNow return two different values inside the same method if the code in between took more than the system's timer resolution of, say, 10 milliseconds?

By extension, is it possible, if the code runs right at the moment that the date turns over into a new day, that DateTime.UtcNow.Date will result in two different dates inside the same method?

答:
Yes, it will return different values.

Following is from Microsoft:

Gets a DateTime object that is set to the current date and time on this computer, expressed as the Coordinated Universal Time (UTC).

Running your code takes time and time is what it returns. So yes, it will change even in same function.


问:
HTML block stored as var javascript
I am trying to store a block of HTML in javascript variable like this,

```<code>var element = <div class="MMinfoboxRoot">
  <div class="MMinfoboxaddress">
    <div>
      <span class="MMrecordName">leicester
      </span>
      <br>
      <span class="MMdaySpan MMdaySpanTitle">Opening Times
      </span>
      <br>
      <br>
      <span class="MMdaysRoot MMdaysmonday">
        <span class="MMdaySpan">Monday:
        </span>
        <span class="MMdayHoursSpan">9am - 8pm
        </span>
      </span>
      <br>
      <span class="MMdaysRoot MMdaystuesday">
        <span class="MMdaySpan">Tuesday:
        </span>
        <span class="MMdayHoursSpan">9am - 8pm
        </span>
      </span>
      <br>
      <span class="MMdaysRoot MMdayswednesday">
        <span class="MMdaySpan">Wednesday:
        </span>
        <span class="MMdayHoursSpan">9am - 8pm
        </span>
      </span>
      <br>
      <span class="MMdaysRoot MMdaysthursday">
        <span class="MMdaySpan">Thursday:
        </span>
        <span class="MMdayHoursSpan">9am - 8pm
        </span>
      </span>
      <br>
      <span class="MMdaysRoot MMdaysfriday">
        <span class="MMdaySpan">Friday:
        </span>
        <span class="MMdayHoursSpan">9am - 8pm
        </span>
      </span>
      <br>
      <span class="MMdaysRoot MMdayssaturday">
        <span class="MMdaySpan">Saturday:
        </span>
        <span class="MMdayHoursSpan">9am - 6pm
        </span>
      </span>
      <br>
      <span class="MMdaysRoot MMdayssunday">
        <span class="MMdaySpan">Sunday:
        </span>
        <span class="MMdayHoursSpan">11am - 5pm
        </span>
      </span>
      <br>
      <br>
      <br>
      <div class="links">
        <strong style="color: rgb(0, 0, 102);">Get directions
        </strong>
        <form onsubmit="GetDirectionsFromInfoBox( this, 0 ); return false;" id="directionsForm-1" method="post" action="" class="directions">
          <label for="infoboxDir1">From
            <input type="text" id="infoboxDir1" value="birstall" class="text">
          </label>
          <input type="image" class="map-submit" src="css/winter-sale-2010/images/multimap/go-button.gif">
        </form>
        <a class="go-to-location" onclick="ZoomToLocation( 0 ); return false;" href="#">Zoom to this location
        </a>
      </div>
    </div>
  </div>
</div>
</code>```

However it is throwing js errors saying unecapuslated strings. How can I do this please?

答:
You need a backslash at the end for string that span multiple lines and some quotes to encapsulate it overall, like this:

```<code>var element = '<div class="MMinfoboxRoot"> \
  <div class="MMinfoboxaddress"> \
  ....';
</code>```

Also as @T.J. points out if you had any ' in the string (or whichever wrapping quotes you used), be sure to use the escaped form, for example \' here.

ContentLicense: CC BY-SA 2.5

Title: HTML block stored as var javascript

Body:
I am trying to store a block of HTML in javascript variable like this,

var element =

      leicester

      Opening Times

        Monday:

        9am - 8pm

        Tuesday:

        9am - 8pm

        Wednesday:

        9am - 8pm

        Thursday:

        9am - 8pm

        Friday:

        9am - 8pm

        Saturday:

        9am - 6pm

        Sunday:

        11am - 5pm

        Get directions

        <form onsubmit="GetDirectionsFromInfoBox( this, 0 ); return false;" id="directionsForm-1" method="post" action="" class="directions">
          From
            <input type="text" id="infoboxDir1" value="birstall" class="text">

          <input type="image" class="map-submit" src="css/winter-sale-2010/images/multimap/go-button.gif">
        </form>
        Zoom to this location

However it is throwing js errors saying unecapuslated strings. How can I do this please?

Body:
You need a backslash at the end for string that span multiple lines and some quotes to encapsulate it overall, like this:

var element = '<div class="MMinfoboxRoot"> \
  <div class="MMinfoboxaddress"> \
  ....';

Also as @T.J. points out if you had any ' in the string (or whichever wrapping quotes you used), be sure to use the escaped form, for example \' here.


问:
How to create a custom home page in XMLUI mirage 2 theme?
all I am working on DSpace 1.6 with XML UI mirage 2 theme, the default installation work fine,  I also know about the overlaying the styles in Mirage 2 theme by placing files in

dspace/modules/xmlui-mirage2 themes.

Generally, What I need is to modify a homepage, so that I can put latest and trending items in a homepage as a banner as shown in world bank home page as shown below.

答:
The following file is used to set content for the home page for an XMLUI site.  Editing this file might resolve your issue.

https://github.com/DSpace/DSpace/blob/master/dspace/config/news-xmlui.xml


问:
Group rows by minimum value
The problem is that I have some tables to build and some values are under an specific threshold. For example:

```<code>    S1  S2  S3
A   700 367 751
B   354 103 143
C   18  7   6
D   27  11  5
E   3   6   1
F   8   2   9
G   1   3   2
</code>```

What I desire is to keep the rows where the values contain at least one value is equal or greater than 10 and merge the rows where the values are less than 10 to create a row named "Other (<10)":

1 - Part of the table with rows with at least one cell containing one value greater than 10 (Row C; value 18):

```<code>    S1  S2  S3
A   700 367 751
B   354 103 143
C   18  7   6
</code>```

2 - Part of the table where any value is greater than 10.

```<code>E   3   6   1
F   8   2   9
G   1   3   2
</code>```

The final table would have the last row with the sum of the columns from E, F, and G, including the "Other(>10)" row name. Like this:

```<code>            S1  S2  S3
A           700 367 751
B           354 103 143
C           18  7   6
D           27  11  5
Other(<10)  12  11  12
</code>```

Title: Group rows by minimum value

Body:
The problem is that I have some tables to build and some values are under an specific threshold. For example:

    S1  S2  S3
A   700 367 751
B   354 103 143
C   18  7   6
D   27  11  5
E   3   6   1
F   8   2   9
G   1   3   2

What I desire is to keep the rows where the values contain at least one value is equal or greater than 10 and merge the rows where the values are less than 10 to create a row named "Other (<10)":

1 - Part of the table with rows with at least one cell containing one value greater than 10 (Row C; value 18):

    S1  S2  S3
A   700 367 751
B   354 103 143
C   18  7   6

2 - Part of the table where any value is greater than 10.

E   3   6   1
F   8   2   9
G   1   3   2

The final table would have the last row with the sum of the columns from E, F, and G, including the "Other(>10)" row name. Like this:

            S1  S2  S3
A           700 367 751
B           354 103 143
C           18  7   6
D           27  11  5
Other(<10)  12  11  12

Body:
A Vectorized option for R would be,

ind <- rowSums(df > 10) == 0

rbind(df[!ind,], colSums(df[ind,]))

#   S1  S2  S3
#A 700 367 751
#B 354 103 143
#C  18   7   6
#D  27  11   5
#   12  11  12


问:
Formatting asynchronous tabs in TKinter?
I have a question about how to format a tkinter program that has to handle multiple tabs that run the same tasks with different input asynchronously?

Right now, I have one class that holds the entire application. Is there a better way to format my application?

I was thinking of putting each tab into a class, which would be in the application class but I'm not sure if is this the best way to do it, like so:

```<code>class Application():
    def __init__(self):
    #code

    class tab1():
        def __init__(self):
            #code

    class tab2():
        def __init__(self):
            #code
</code>```

I am new to GUI programming so I applogize if this question is too broad.

答:
From what I can see you have 2 problems related to this question.

One is the issue of have 3 separate tabs/widgets.

This is easy enough to accomplish. You can do this using 1 function with several variables that you are changing between each of your 3 processes and then call the function 3 times with those different variables.

```<code>def doStuff(var1, var2, var3):
    sumvars = var1 - var2 * var3
    return sumvars

print(doStuff(1,2,3), doStuff(3,2,1), doStuff(2,3,1))
</code>```

Result:

```<code>-5 1 -1
</code>```

As you can see this is 3 different processes ran from the same defined function

You can accomplish this with a class. You only need one class that has the variables in questions as arguments. You can call that class 3 different times with the different variables you need to have worked on.

```<code>class DoStuff(object):
    def __init__(self, var1, var2, var3):
        self.var1 = var1
        self.var2 = var2
        self.var3 = var3

    def someMath(self):
        sumvars = self.var1 - self.var2 * self.var3
        return sumvars

object1 = DoStuff(1,2,3)
object2 = DoStuff(3,2,1)
object3 = DoStuff(2,3,1)

print(object1.someMath(), object2.someMath(), object3.someMath())
</code>```

Result:

```<code>-5 1 -1
</code>```

Update:

From my research you might want to take a look at multiprocessing library.

If you look at this post there was a user with a similar problem and they discovered using the multiprocessing  library that each process does in fact have its own Process ID and is running in parallel from what I read.

Here is a link to the documentation on multiprocessing

Body:
I have a question about how to format a tkinter program that has to handle multiple tabs that run the same tasks with different input asynchronously?

Right now, I have one class that holds the entire application. Is there a better way to format my application?

I was thinking of putting each tab into a class, which would be in the application class but I'm not sure if is this the best way to do it, like so:

class Application():
    def __init__(self):
    #code

    class tab1():
        def __init__(self):
            #code

    class tab2():
        def __init__(self):
            #code

I am new to GUI programming so I applogize if this question is too broad.

Body:
From what I can see you have 2 problems related to this question.

One is the issue of have 3 separate tabs/widgets.

This is easy enough to accomplish. You can do this using 1 function with several variables that you are changing between each of your 3 processes and then call the function 3 times with those different variables.

def doStuff(var1, var2, var3):
    sumvars = var1 - var2 * var3
    return sumvars

print(doStuff(1,2,3), doStuff(3,2,1), doStuff(2,3,1))

Result:

-5 1 -1

As you can see this is 3 different processes ran from the same defined function

You can accomplish this with a class. You only need one class that has the variables in questions as arguments. You can call that class 3 different times with the different variables you need to have worked on.

class DoStuff(object):
    def __init__(self, var1, var2, var3):
        self.var1 = var1
        self.var2 = var2
        self.var3 = var3

    def someMath(self):
        sumvars = self.var1 - self.var2 * self.var3
        return sumvars

object1 = DoStuff(1,2,3)
object2 = DoStuff(3,2,1)
object3 = DoStuff(2,3,1)

print(object1.someMath(), object2.someMath(), object3.someMath())

Result:

-5 1 -1

Update:

From my research you might want to take a look at multiprocessing library.

If you look at this post there was a user with a similar problem and they discovered using the multiprocessing  library that each process does in fact have its own Process ID and is running in parallel from what I read.

Here is a link to the documentation on multiprocessing


问:
navigation menu top and bottom,no drop up at the bottom

<!DOCTYPE html>

    Sales

      Link 1
      Link 2
      Link 3

    Search

      Link 1
      Link 2
      Link 3

    Transfers

      Link 1
      Link 2
      Link 3

   Returns

      Link 1
      Link 2
      Link 3

<ulf>
<lif class="dropup">
    Order

      Link 1
      Link 2
      Link 3

  </lif>
<lif class="dropup">
    Reports

      Link 1
      Link 2
      Link 3

  </lif>
  <lif class="dropup">
    Exports/Imports

      Link 1
      Link 2
      Link 3

  </lif>
   <lif class="dropup">
   Settings

      Link 1
      Link 2
      Link 3

 </lif>

</ulf>

```

The top navigation is working properly. I mean the drop down is functional,but the bottom navigation isn't working. I want to do something like drop up. Can someone please check the code and give me some instruction on what i have to do?

答:
Two things:

1.) Add bottom: 0 to .dropup-content to align the submenus to the bottom of their container, not the top.

2.) Add overflow-visible to ulf

ul {
  list-style-type: none;
  margin: 0;
  padding: 0;
  overflow: hidden;
  background-color: #333;
}

li {
  float: left;
}

li a,
.dropbtn {
  display: inline-block;
  color: white;
  text-align: center;
  padding: 14px 16px;
  text-decoration: none;
}

li a:hover,
.dropdown:hover .dropbtn {
  background-color: red;
}

li.dropdown {
  display: inline-block;
}

.dropdown-content {
  display: none;
  position: absolute;
  background-color: #f9f9f9;
  min-width: 160px;
  box-shadow: 0px 8px 16px 0px rgba(0, 0, 0, 0.2);
  z-index: 1;
}

.dropdown-content a {
  color: black;
  padding: 12px 16px;
  text-decoration: none;
  display: block;
  text-align: left;
}

.dropdown-content a:hover {
  background-color: #f1f1f1
}

.dropdown:hover .dropdown-content {
  display: block;
}

ulf {
  list-style-type: none;
  margin: 0;
  padding: 0;
  overflow: hidden;
  background-color: #333;
  position: fixed;
  bottom: 0%;
  width: 100%;
  overflow: visible;
}

lif {
  float: left;
  border-right: 1px solid #bbb;
}

lif a,
.dropbtn {
  display: inline-block;
  color: white;
  text-align: center;
  padding: 14px 16px;
  text-decoration: none;
}

lif a:hover,
.dropup:hover .dropbtn {
  background-color: red;
}

lif.dropup {
  display: inline-block;
}

.dropup-content {
  display: none;
  position: absolute;
  background-color: #f9f9f9;
  min-width: 160px;
  box-shadow: 0px 8px 16px 0px rgba(0, 0, 0, 0.2);
  z-index: 1;
  bottom: 0;
}

.dropup-content a {
  color: black;
  padding: 12px 16px;
  text-decoration: none;
  display: block;
  text-align: left;
}

.dropup-content a:hover {
  background-color: #f1f1f1
}

.dropup:hover .dropup-content {
  display: block;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><!DOCTYPE html>
<html>

<body>

  <ul>
    </li>
    <li class="dropdown">
      Sales
      <div class="dropdown-content">
        Link 1
        Link 2
        Link 3
      </div>
    </li>
    <li class="dropdown">
      Search
      <div class="dropdown-content">
        Link 1
        Link 2
        Link 3
      </div>
    </li>
    <li class="dropdown">
      Transfers
      <div class="dropdown-content">
        Link 1
        Link 2
        Link 3
      </div>
    </li>
    <li class="dropdown">
      Returns
      <div class="dropdown-content">
        Link 1
        Link 2
        Link 3
      </div>
    </li>

  </ul>

  <ulf>
    <lif class="dropup">
      Order
      <div class="dropup-content">
        Link 1
        Link 2
        Link 3
      </div>
    </lif>
    <lif class="dropup">
      Reports
      <div class="dropup-content">
        Link 1
        Link 2
        Link 3
      </div>
    </lif>
    <lif class="dropup">
      Exports/Imports
      <div class="dropup-content">
        Link 1
        Link 2
        Link 3
      </div>
    </lif>
    <lif class="dropup">
      Settings
      <div class="dropup-content">
        Link 1
        Link 2
        Link 3
      </div>
    </lif>

  </ulf>

</body>

</html></code>```

Body:
<!DOCTYPE html>

    Sales

      Link 1
      Link 2
      Link 3

    Search

      Link 1
      Link 2
      Link 3

    Transfers

      Link 1
      Link 2
      Link 3

   Returns

      Link 1
      Link 2
      Link 3

<ulf>
<lif class="dropup">
    Order

      Link 1
      Link 2
      Link 3

  </lif>
<lif class="dropup">
    Reports

      Link 1
      Link 2
      Link 3

  </lif>
  <lif class="dropup">
    Exports/Imports

      Link 1
      Link 2
      Link 3

  </lif>
   <lif class="dropup">
   Settings

      Link 1
      Link 2
      Link 3

 </lif>

</ulf>

The top navigation is working properly. I mean the drop down is functional,but the bottom navigation isn't working. I want to do something like drop up. Can someone please check the code and give me some instruction on what i have to do?

Body:
Two things:

1.) Add bottom: 0 to .dropup-content to align the submenus to the bottom of their container, not the top.

2.) Add overflow-visible to ulf

ul {
  list-style-type: none;
  margin: 0;
  padding: 0;
  overflow: hidden;
  background-color: #333;
}

li {
  float: left;
}

li a,
.dropbtn {
  display: inline-block;
  color: white;
  text-align: center;
  padding: 14px 16px;
  text-decoration: none;
}

li a:hover,
.dropdown:hover .dropbtn {
  background-color: red;
}

li.dropdown {
  display: inline-block;
}

.dropdown-content {
  display: none;
  position: absolute;
  background-color: #f9f9f9;
  min-width: 160px;
  box-shadow: 0px 8px 16px 0px rgba(0, 0, 0, 0.2);
  z-index: 1;
}

.dropdown-content a {
  color: black;
  padding: 12px 16px;
  text-decoration: none;
  display: block;
  text-align: left;
}

.dropdown-content a:hover {
  background-color: #f1f1f1
}

.dropdown:hover .dropdown-content {
  display: block;
}

ulf {
  list-style-type: none;
  margin: 0;
  padding: 0;
  overflow: hidden;
  background-color: #333;
  position: fixed;
  bottom: 0%;
  width: 100%;
  overflow: visible;
}

lif {
  float: left;
  border-right: 1px solid #bbb;
}

lif a,
.dropbtn {
  display: inline-block;
  color: white;
  text-align: center;
  padding: 14px 16px;
  text-decoration: none;
}

lif a:hover,
.dropup:hover .dropbtn {
  background-color: red;
}

lif.dropup {
  display: inline-block;
}

.dropup-content {
  display: none;
  position: absolute;
  background-color: #f9f9f9;
  min-width: 160px;
  box-shadow: 0px 8px 16px 0px rgba(0, 0, 0, 0.2);
  z-index: 1;
  bottom: 0;
}

.dropup-content a {
  color: black;
  padding: 12px 16px;
  text-decoration: none;
  display: block;
  text-align: left;
}

.dropup-content a:hover {
  background-color: #f1f1f1
}

.dropup:hover .dropup-content {
  display: block;
}

<!DOCTYPE html>
<html>

<body>

  <ul>
    </li>
    <li class="dropdown">
      <a href="javascript:void(0)" class="dropbtn">Sales</a>
      <div class="dropdown-content">
        <a href="#">Link 1</a>
        <a href="#">Link 2</a>
        <a href="#">Link 3</a>
      </div>
    </li>
    <li class="dropdown">
      <a href="javascript:void(0)" class="dropbtn">Search</a>
      <div class="dropdown-content">
        <a href="#">Link 1</a>
        <a href="#">Link 2</a>
        <a href="#">Link 3</a>
      </div>
    </li>
    <li class="dropdown">
      <a href="javascript:void(0)" class="dropbtn">Transfers</a>
      <div class="dropdown-content">
        <a href="#">Link 1</a>
        <a href="#">Link 2</a>
        <a href="#">Link 3</a>
      </div>
    </li>
    <li class="dropdown">
      <a href="javascript:void(0)" class="dropbtn">Returns</a>
      <div class="dropdown-content">
        <a href="#">Link 1</a>
        <a href="#">Link 2</a>
        <a href="#">Link 3</a>
      </div>
    </li>

  </ul>

  <ulf>
    <lif class="dropup">
      <a href="javascript:void(0)" class="dropbtn">Order</a>
      <div class="dropup-content">
        <a href="#">Link 1</a>
        <a href="#">Link 2</a>
        <a href="#">Link 3</a>
      </div>
    </lif>
    <lif class="dropup">
      <a href="javascript:void(0)" class="dropbtn">Reports</a>
      <div class="dropup-content">
        <a href="#">Link 1</a>
        <a href="#">Link 2</a>
        <a href="#">Link 3</a>
      </div>
    </lif>
    <lif class="dropup">
      <a href="javascript:void(0)" class="dropbtn">Exports/Imports</a>
      <div class="dropup-content">
        <a href="#">Link 1</a>
        <a href="#">Link 2</a>
        <a href="#">Link 3</a>
      </div>
    </lif>
    <lif class="dropup">
      <a href="javascript:void(0)" class="dropbtn">Settings</a>
      <div class="dropup-content">
        <a href="#">Link 1</a>
        <a href="#">Link 2</a>
        <a href="#">Link 3</a>
      </div>
    </lif>

  </ulf>

</body>

</html>


答:
Why not carry out an experiment?

```<code>  DateTime t1 = DateTime.UtcNow;

  while (true) {
    DateTime t2 = DateTime.UtcNow;

    if (t2 != t1) {
      Console.Write($"{(t2 - t1).TotalMilliseconds}");

      break;
    }
  }
</code>```

Outcome:

```<code>  1.0001
</code>```

So, at my workstation DateTime.UtcNow has a resolution of 1 millisecond. And if the method takes 10 ms to complete, DateTime.UtcNow will definetely return the different values:

```<code>  DateTime t1 = DateTime.UtcNow;

  // 10 ms routine here
  DoSomething();

  // t1 != t2; t2 ~ t1.AddMilliseconds(10)
  DateTime t2 = DateTime.UtcNow;
</code>```

There's minuscule probability that some PCs don't have High Resilution Timer Stopwatch.IsHighResolution; in this case the resolution drops to 3600 / 65536 * 1000 = 55 ms (System Timer resolution - 65536 ticks per hour) and there's a good chance that both t1 and t2 will be the same

Title: Will DateTime.UtcNow return different values within the same method?

Body:
Say that I have a long loop of simple math in between two calls to DateTime.UtcNow in a single method.

Does DateTime.UtcNow return two different values inside the same method if the code in between took more than the system's timer resolution of, say, 10 milliseconds?

By extension, is it possible, if the code runs right at the moment that the date turns over into a new day, that DateTime.UtcNow.Date will result in two different dates inside the same method?

Body:
Why not carry out an experiment?

  DateTime t1 = DateTime.UtcNow;

  while (true) {
    DateTime t2 = DateTime.UtcNow;

    if (t2 != t1) {
      Console.Write($"{(t2 - t1).TotalMilliseconds}");

      break;
    }
  }

Outcome:

  1.0001

So, at my workstation DateTime.UtcNow has a resolution of 1 millisecond. And if the method takes 10 ms to complete, DateTime.UtcNow will definetely return the different values:

  DateTime t1 = DateTime.UtcNow;

  // 10 ms routine here
  DoSomething();

  // t1 != t2; t2 ~ t1.AddMilliseconds(10)
  DateTime t2 = DateTime.UtcNow;

There's minuscule probability that some PCs don't have High Resilution Timer Stopwatch.IsHighResolution; in this case the resolution drops to 3600 / 65536 * 1000 = 55 ms (System Timer resolution - 65536 ticks per hour) and there's a good chance that both t1 and t2 will be the same


问:
Spring Data Rest custom controller with patch method - how to merge resource with entity
By default when we have a repository with save method exposed we can do a PATCH request. Then Spring Data REST retrieves the original object from the database and apply changes to entity and then saves it for us (inside JsonPatchHandler class). This allows us to do the following request for class

```<code>class Address {
     Long id;
     String street;
     Long houseNumber;
}
</code>```

PATCH /api/addresses/1 with body

```<code>{ houseNumber: 123 }
</code>```

And only this one field will be changed.

Now having custom controller we would like to in the update method receive the whole object (after HATEOAS merged it with the original object from the DB)

```<code>@RepositoryRestController
@ExposesResourceFor(Address.class)
@ResponseBody
@RequestMapping("/addresses")
public class AdddressController {

    @PatchMapping("/{addressId}")
    public Resource<Address> update(@RequestBody Resource<Address> addressResource, @PathVariable Long addressId) {
        Address address= addressResource.getContent();
        // .... some logic
        address = addressRepository.save(address);
        return new Resource<>(address);
    }
}
</code>```

Unfortunately in the place where I would do some logic I get the Address with null fields instead of the merged object.

Is it possible to plug the custom controller in the Spring Data REST stack so that when patching the request it will merge it for me (as it does for normal repositories)?

edit:
I would like to find a solution that works transparently both with PATCH(content-type:application/json-patch+json) and PATCH(content-type: application/hal+json)

答:
After browsing the Spring sources I haven't found a reasonable solution. As a result I've created issue in their - JIRA

For the moment the only reasonable workaround is following - create custom controller that has PersitentEntityResource as a parameter and has both {id} and {repository} placeholders in its path i.e.

```<code>@PatchMapping("/addresses/{id}/{repository}")
public Resource<Address> update(PersistentEntityResource addressResource) {
    ...
}
</code>```

which makes the invocation endpoint /addresses/123/addresses

Body:
By default when we have a repository with save method exposed we can do a PATCH request. Then Spring Data REST retrieves the original object from the database and apply changes to entity and then saves it for us (inside JsonPatchHandler class). This allows us to do the following request for class

class Address {
     Long id;
     String street;
     Long houseNumber;
}

PATCH /api/addresses/1 with body

{ houseNumber: 123 }

And only this one field will be changed.

Now having custom controller we would like to in the update method receive the whole object (after HATEOAS merged it with the original object from the DB)

@RepositoryRestController
@ExposesResourceFor(Address.class)
@ResponseBody
@RequestMapping("/addresses")
public class AdddressController {

    @PatchMapping("/{addressId}")
    public Resource<Address> update(@RequestBody Resource<Address> addressResource, @PathVariable Long addressId) {
        Address address= addressResource.getContent();
        // .... some logic
        address = addressRepository.save(address);
        return new Resource<>(address);
    }
}

Unfortunately in the place where I would do some logic I get the Address with null fields instead of the merged object.

Is it possible to plug the custom controller in the Spring Data REST stack so that when patching the request it will merge it for me (as it does for normal repositories)?

edit:
I would like to find a solution that works transparently both with PATCH(content-type:application/json-patch+json) and PATCH(content-type: application/hal+json)

Body:
After browsing the Spring sources I haven't found a reasonable solution. As a result I've created issue in their - JIRA

For the moment the only reasonable workaround is following - create custom controller that has PersitentEntityResource as a parameter and has both {id} and {repository} placeholders in its path i.e.

@PatchMapping("/addresses/{id}/{repository}")
public Resource<Address> update(PersistentEntityResource addressResource) {
    ...
}

which makes the invocation endpoint /addresses/123/addresses


问:
Python - how to use few times the same next iteration?
I would like to search a list:

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

and replace/edit items different from the previous item and next item. For xxample: I want to get rid of/edit 1 at index 2 in the list above.

Take a look at my code below and please continue reading my core question beneath my code:

!Update: Result should be: [0, 0, 0, 0, 1, 1, 1, 1, 1, 1]

```<code>x = [0, 0, 1, 0, 1, 1, 1, 0, 1, 1]
print(x)
hiter = iter(x)
next(hiter)
prev = None

for i in x:
    try:
        print('prev %s - CURRENT %s - next %s' % (prev, i, next(hiter)))
        prev = i

        #if i != prev and i != next(hiter):
        #   x[i] = prev

    except StopIteration:
        break

print(x)
</code>```

We know the previous item, the next item and the current item.

But everytime I use:

```
if i != prev and <b>i != next(hiter)</b>...
```

the next(hiter) destroys order. In other words, if I use next(hiter) more than 1 time in my loop, Python reads the next item as double, because I used next(hiter) two times in a loop.

I tried also declare seperate variable like y = next(hiter) - but still it didn't work (obviously won't work but I was desperate to check it anyway xD).

I have no clues, in addition, hiter.__next__() does the same as next(hiter).

答:
You probably want to access your list elements via indexing. In your loop you can then access the previous and next items by adding or subtracting to the current index.

Remember that in a list you can access an element with hiter[0], hiter[1], ..., and in the loop as:

```<code>for i in range(len(hiter)-1):
    print("The item is %s" % hiter[i])
</code>```

and so you can then access the previous and next, only needing to take care of the edge cases (to keep the index from moving out of range). An approach would be:

```<code>for i in range(len(hiter)):
    if 0 < i < (len(hiter) - 1):
        print("The items are %s, %s, %s" % (hiter[i-1], hiter[i], hiter[i+1]))
    elif i == 0:
        print("The items are %s, %s" % (hiter[i], hiter[i+1]))
    elif i == (len(hiter) - 1):
        print("The items are %s, %s" % (hiter[i-1], hiter[i]))
</code>```

In the same fashion, you can change the values in your mutable list with the same indexing methods.

Body:
I would like to search a list:

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

and replace/edit items different from the previous item and next item. For xxample: I want to get rid of/edit 1 at index 2 in the list above.

Take a look at my code below and please continue reading my core question beneath my code:

!Update: Result should be: [0, 0, 0, 0, 1, 1, 1, 1, 1, 1]

x = [0, 0, 1, 0, 1, 1, 1, 0, 1, 1]
print(x)
hiter = iter(x)
next(hiter)
prev = None

for i in x:
    try:
        print('prev %s - CURRENT %s - next %s' % (prev, i, next(hiter)))
        prev = i

        #if i != prev and i != next(hiter):
        #   x[i] = prev

    except StopIteration:
        break

print(x)

We know the previous item, the next item and the current item.

But everytime I use:

if i != prev and i != next(hiter)...

the next(hiter) destroys order. In other words, if I use next(hiter) more than 1 time in my loop, Python reads the next item as double, because I used next(hiter) two times in a loop.

I tried also declare seperate variable like y = next(hiter) - but still it didn't work (obviously won't work but I was desperate to check it anyway xD).

I have no clues, in addition, hiter.__next__() does the same as next(hiter).

Body:
You probably want to access your list elements via indexing. In your loop you can then access the previous and next items by adding or subtracting to the current index.

Remember that in a list you can access an element with hiter[0], hiter[1], ..., and in the loop as:

for i in range(len(hiter)-1):
    print("The item is %s" % hiter[i])

and so you can then access the previous and next, only needing to take care of the edge cases (to keep the index from moving out of range). An approach would be:

for i in range(len(hiter)):
    if 0 < i < (len(hiter) - 1):
        print("The items are %s, %s, %s" % (hiter[i-1], hiter[i], hiter[i+1]))
    elif i == 0:
        print("The items are %s, %s" % (hiter[i], hiter[i+1]))
    elif i == (len(hiter) - 1):
        print("The items are %s, %s" % (hiter[i-1], hiter[i]))

In the same fashion, you can change the values in your mutable list with the same indexing methods.


问:
how to know how many times its a value in the databes? and for all values?
This can be aplied to tags, to coments, ...

My question its to obtain for example, top 20 repetitions for an atribute in  a table..

I mean, i know i can ask for a selected atribute with the mysql_num_rows, but how do i do it to know all of them?

For example,

Most popular colors:
Red -100000
blue -5000
white -200
and so on...

if anyone can give me a clue.. thanks!

答:
You want to do this computation on the database, not in your application. Usually, a query of the following form should be fine:

```<code>SELECT color_id, COUNT(product_id) AS number
FROM products
GROUP BY color_id
ORDER BY number DESC
LIMIT 20
</code>```

It will be faster this way, as only the value-count data will be sent from the database to the application. Also, if you have indices set up correctly (on color_id, for instance), thighs will be smoother.

Body:
You want to do this computation on the database, not in your application. Usually, a query of the following form should be fine:

SELECT color_id, COUNT(product_id) AS number
FROM products
GROUP BY color_id
ORDER BY number DESC
LIMIT 20

It will be faster this way, as only the value-count data will be sent from the database to the application. Also, if you have indices set up correctly (on color_id, for instance), thighs will be smoother.


问:
Implement Multisite in wordpress in sub directories
I am trying to implement multisite so that I can add several other blogs.

I added define('WP_ALLOW_MULTISITE', true); line of code in wp-config.php file under define('WPLANG', '');

When I look at the configure network panel I get this message:

"Because your install is not new, the sites in your WordPress network must use sub-domains. The main site in a sub-directory install will need to use a modified permalink structure, potentially breaking existing links."

I want all my blogs to be in sub directories.

```<code>Like : http://abcd.com/site1, http://abcd.com/site2, http://abcd.com/site3
</code>```

What should I do so that I can proceed with installing the multisite option using sub directories?

答:
Hi Try adding the following code in your themes functions.php . It w

```<code>add_filter( 'allow_subdirectory_install',
create_function( '', 'return true;' )
);
</code>```

That’s it. Now reload the Network page and you will see option to choose between sub-domain and sub-directory. Once done remove the code from functions.php.

Source tip credit

Body:
I am trying to implement multisite so that I can add several other blogs.

I added define('WP_ALLOW_MULTISITE', true); line of code in wp-config.php file under define('WPLANG', '');

When I look at the configure network panel I get this message:

"Because your install is not new, the sites in your WordPress network must use sub-domains. The main site in a sub-directory install will need to use a modified permalink structure, potentially breaking existing links."

I want all my blogs to be in sub directories.

Like : http://abcd.com/site1, http://abcd.com/site2, http://abcd.com/site3

What should I do so that I can proceed with installing the multisite option using sub directories?

Body:
Hi Try adding the following code in your themes functions.php . It w

add_filter( 'allow_subdirectory_install',
create_function( '', 'return true;' )
);

That’s it. Now reload the Network page and you will see option to choose between sub-domain and sub-directory. Once done remove the code from functions.php.

Source tip credit


问:
Spring Boot : Getting IllegalArgumentException in WLS
I am trying to deploy spring boot as war in WLS 12 C and I am getting the below error,
I have skipped logging in pom.xml

```<code>          <exclusions>
                <exclusion>
                    <groupId>org.springframework.boot</groupId>
                    <artifactId>spring-boot-starter-logging</artifactId>
                </exclusion>
            </exclusions>
</code>```

and I have the below code in weblogic.xml

```<code> <wls:container-descriptor>
            <wls:prefer-application-packages>
                <wls:package-name>org.slf4j.*</wls:package-name>
            </wls:prefer-application-packages>
        </wls:container-descriptor>
</code>```

Please suggest is there any solution for the below Error

```<code>java.lang.IllegalArgumentException: Object of class [null] must be an instance of interface javax.management.MBeanServer
</code>```

I have tried the below example

```<code>https://github.com/purrox/Spring-example
</code>```

答:
The sample project spring-example is using a very old version of spring-boot:1.0.0.RC4. If you are using the same version as the sample project I advise you to upgrade to the latest stable spring-boot version 1.5.3

Edit

To deploy a Spring Boot application to WebLogic you must ensure that your servlet initializer directly implements WebApplicationInitializer (even if you extend from a base class that already implements it).

A typical initializer for WebLogic would be something like this:

```<code>import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.context.web.SpringBootServletInitializer;
import org.springframework.web.WebApplicationInitializer;

@SpringBootApplication
public class MyApplication extends SpringBootServletInitializer implements WebApplicationInitializer {

}
</code>```

Please refer to spring-boot documentation for Deploying a WAR to WebLogic

Body:
I am trying to deploy spring boot as war in WLS 12 C and I am getting the below error,
I have skipped logging in pom.xml

          <exclusions>
                <exclusion>
                    <groupId>org.springframework.boot</groupId>
                    <artifactId>spring-boot-starter-logging</artifactId>
                </exclusion>
            </exclusions>

and I have the below code in weblogic.xml

 <wls:container-descriptor>
            <wls:prefer-application-packages>
                <wls:package-name>org.slf4j.*</wls:package-name>
            </wls:prefer-application-packages>
        </wls:container-descriptor>

Please suggest is there any solution for the below Error

java.lang.IllegalArgumentException: Object of class [null] must be an instance of interface javax.management.MBeanServer

I have tried the below example

https://github.com/purrox/Spring-example

Body:
The sample project spring-example is using a very old version of spring-boot:1.0.0.RC4. If you are using the same version as the sample project I advise you to upgrade to the latest stable spring-boot version 1.5.3

Edit

To deploy a Spring Boot application to WebLogic you must ensure that your servlet initializer directly implements WebApplicationInitializer (even if you extend from a base class that already implements it).

A typical initializer for WebLogic would be something like this:

import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.context.web.SpringBootServletInitializer;
import org.springframework.web.WebApplicationInitializer;

@SpringBootApplication
public class MyApplication extends SpringBootServletInitializer implements WebApplicationInitializer {

}

Please refer to spring-boot documentation for Deploying a WAR to WebLogic


问:
Assigning word from text file to array
```<code>person1 bob
person2 george
person3 tom
</code>```

This is a project on VB. I am attempting to read off a text file such as the above and assign the second word on each line to an array. For example, array(1) would be "bob", array(2) would have "george", and array(3) would have "tom". I am currently having trouble with assigning to arrays as my current output for array(1) is:

```<code>bob
george
tom
</code>```

My current attempt is:

```<code>Dim FileName As String = "*snip*"
Dim FileReader As StreamReader = File.OpenText(FileName)
Dim FileLine As String = FileReader.ReadLine()
For x = 1 To 18
    Dim players() As String = FileLine.Split(New Char() {" "c})
    FileLine = FileReader.ReadLine()
    Console.WriteLine(players(1))
    count = count + 1
Next
</code>```

I'm a total noob, please treat me well.

答:
Can i provide you a much simpler way using LINQ?

```<code>Dim resultArray = File.ReadLines(FileName).
   Select(Function(l) l.Split({" "c}, StringSplitOptions.RemoveEmptyEntries).Last().Trim()).
   ToArray()
</code>```

If a line could contain more than two "words" you could use ElementAtOrDefault(1) instead of Last to access the second one (if available, otherwise it's Nothing).

Title: Assigning word from text file to array

Body:
person1 bob
person2 george
person3 tom

This is a project on VB. I am attempting to read off a text file such as the above and assign the second word on each line to an array. For example, array(1) would be "bob", array(2) would have "george", and array(3) would have "tom". I am currently having trouble with assigning to arrays as my current output for array(1) is:

bob
george
tom

My current attempt is:

Dim FileName As String = "*snip*"
Dim FileReader As StreamReader = File.OpenText(FileName)
Dim FileLine As String = FileReader.ReadLine()
For x = 1 To 18
    Dim players() As String = FileLine.Split(New Char() {" "c})
    FileLine = FileReader.ReadLine()
    Console.WriteLine(players(1))
    count = count + 1
Next

I'm a total noob, please treat me well.

Body:
Can i provide you a much simpler way using LINQ?

Dim resultArray = File.ReadLines(FileName).
   Select(Function(l) l.Split({" "c}, StringSplitOptions.RemoveEmptyEntries).Last().Trim()).
   ToArray()

If a line could contain more than two "words" you could use ElementAtOrDefault(1) instead of Last to access the second one (if available, otherwise it's Nothing).


问:
How to get the Firebase download url of the image being uploaded?
I'm using this code below to upload an image to firebase storage but when the image is uploaded I would like to be able to recall the image using the download url. Is this possible?

ViewUserMapActivity

```<code>package uk.co.jaunt_app.jaunt;

import android.app.ProgressDialog;
import android.content.Intent;
import android.graphics.Bitmap;
import android.location.Location;
import android.net.Uri;
import android.os.Bundle;
import android.provider.MediaStore;
import android.support.annotation.NonNull;
import android.support.v4.app.FragmentActivity;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.google.android.gms.maps.CameraUpdateFactory;
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.OnMapReadyCallback;
import com.google.android.gms.maps.SupportMapFragment;
import com.google.android.gms.maps.model.BitmapDescriptorFactory;
import com.google.android.gms.maps.model.LatLng;
import com.google.android.gms.maps.model.MapStyleOptions;
import com.google.android.gms.maps.model.MarkerOptions;
import com.google.android.gms.tasks.OnFailureListener;
import com.google.android.gms.tasks.OnSuccessListener;
import com.google.firebase.storage.FirebaseStorage;
import com.google.firebase.storage.StorageReference;
import com.google.firebase.storage.UploadTask;

import java.util.UUID;

import static uk.co.jaunt_app.jaunt.R.id.MapDistance;
import static uk.co.jaunt_app.jaunt.R.id.map;

public class ViewUserMapActivity extends FragmentActivity implements OnMapReadyCallback {

    private GoogleMap mMap;
    Button HomeButt;
    TextView MapName;
    TextView MapStartLocLat;
    TextView MapStartLocLong;
    TextView MapEndLocLat;
    TextView MapEndLocLong;
    TextView mapDistance;
    Button chooseImg, uploadImg;
    ImageView imgView;
    int PICK_IMAGE_REQUEST = 111;
    Uri filePath;
    ProgressDialog pd;
    TextView imgUrl;

    FirebaseStorage storage = FirebaseStorage.getInstance();
    StorageReference storageRef = storage.getReferenceFromUrl("gs://jaunt-ddc86.appspot.com/");

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_view_user_map);
        SupportMapFragment mapFragment = (SupportMapFragment) getSupportFragmentManager()
                .findFragmentById(map);
        mapFragment.getMapAsync(this);

        HomeButt = (Button) findViewById(R.id.backHome);
        MapName = (TextView) findViewById(R.id.MapName);
        MapStartLocLat = (TextView) findViewById(R.id.MapStartLocLat);
        MapStartLocLong = (TextView) findViewById(R.id.MapStartLocLong);
        MapEndLocLat = (TextView) findViewById(R.id.MapEndLocLat);
        MapEndLocLong = (TextView) findViewById(R.id.MapEndLocLong);
        mapDistance = (TextView) findViewById(MapDistance);
        imgUrl = (TextView) findViewById(R.id.imgurl);

        Intent intent = getIntent();
        final String mapName = intent.getStringExtra("mapName");
        String mapStartLat = intent.getStringExtra("mapStartLat");
        String mapStartLong = intent.getStringExtra("mapStartLong");
        String mapEndLat = intent.getStringExtra("mapEndLat");
        String mapEndLong = intent.getStringExtra("mapEndLong");
        MapName.setText(mapName);
        MapStartLocLat.setText(mapStartLat);
        MapStartLocLong.setText(mapStartLong);
        MapEndLocLat.setText(mapEndLat);
        MapEndLocLong.setText(mapEndLong);

        chooseImg = (Button)findViewById(R.id.chooseImg);
        uploadImg = (Button)findViewById(R.id.uploadImg);
        imgView = (ImageView)findViewById(R.id.imgView);

        pd = new ProgressDialog(this);
        pd.setMessage("Uploading....");

        chooseImg.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent();
                intent.setType("image/*");
                intent.setAction(Intent.ACTION_PICK);
                startActivityForResult(Intent.createChooser(intent, "Select Image"), PICK_IMAGE_REQUEST);
            }
        });

        uploadImg.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if(filePath != null) {
                    pd.show();
                    String imageID = UUID.randomUUID().toString();
                    StorageReference childRef = storageRef.child(imageID);

                    //uploading the image
                    UploadTask uploadTask = childRef.putFile(filePath);

                    uploadTask.addOnSuccessListener(new OnSuccessListener<UploadTask.TaskSnapshot>() {
                        @Override
                        public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {
                            pd.dismiss();
                            Toast.makeText(ViewUserMapActivity.this, "Image Uploaded Successfully", Toast.LENGTH_LONG).show();
                        }

                    }).addOnFailureListener(new OnFailureListener() {
                        @Override
                        public void onFailure(@NonNull Exception e) {
                            pd.dismiss();
                            Toast.makeText(ViewUserMapActivity.this, "Upload Failed -> " + e, Toast.LENGTH_LONG).show();
                        }
                    });

                }
                else {
                    Toast.makeText(ViewUserMapActivity.this, "Select An Image", Toast.LENGTH_LONG).show();
                }
            }
        });
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);

        if (requestCode == PICK_IMAGE_REQUEST && resultCode == RESULT_OK && data != null && data.getData() != null) {
            filePath = data.getData();

            try {
                //getting image from gallery
                Bitmap bitmap = MediaStore.Images.Media.getBitmap(getContentResolver(), filePath);
                //Setting image to ImageView
                imgView.setImageBitmap(bitmap);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }

    }

    @Override
    public void onMapReady(GoogleMap googleMap) {
        mMap = googleMap;
        googleMap.setMapStyle(MapStyleOptions.loadRawResourceStyle(this, R.raw.style_json));

        String mapstartlat = MapStartLocLat.getText().toString().trim();
        String mapstartlong = MapStartLocLong.getText().toString().trim();
        String mapendlat = MapEndLocLat.getText().toString().trim();
        String mapendlong = MapEndLocLong.getText().toString().trim();

        double startlat = Double.valueOf(mapstartlat);
        double startlong = Double.valueOf(mapstartlong);
        double endlat = Double.valueOf(mapendlat);
        double endlong = Double.valueOf(mapendlong);

        LatLng Start = new LatLng(startlat, startlong);
        LatLng End = new LatLng(endlat, endlong);
        mMap.addMarker(new MarkerOptions().position(Start)
                .icon(BitmapDescriptorFactory.fromResource(R.drawable.mappin)));
        mMap.addMarker(new MarkerOptions().position(End)
                .icon(BitmapDescriptorFactory.fromResource(R.drawable.mappin)));
        mMap.moveCamera(CameraUpdateFactory.newLatLngZoom(End, 6 ));

        Location loc1 = new Location("");
        loc1.setLatitude(startlat);
        loc1.setLongitude(startlong);

        Location loc2 = new Location("");
        loc2.setLatitude(endlat);
        loc2.setLongitude(endlong);

        float distanceInMeters = loc1.distanceTo(loc2);
        Double value = 0.00062137;
        Double distanceValue = (distanceInMeters)*value;
        mapDistance.setText(String.format("%.1f mi", distanceValue));

        HomeButt.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(ViewUserMapActivity.this, MainActivity.class);
                startActivity(intent);
            }
        });

    }

}
</code>```

答:
From the Firebase documentation on uploading files:

You can upload local files on the device, such as photos and videos from the camera, with the putFile() method. putFile() takes a File and returns an UploadTask which you can use to manage and monitor the status of the upload.

```<code>Uri file = Uri.fromFile(new File("path/to/images/rivers.jpg"));
StorageReference riversRef = storageRef.child("images/"+file.getLastPathSegment());
uploadTask = riversRef.putFile(file);

Task<Uri> urlTask = uploadTask.continueWithTask(new Continuation<UploadTask.TaskSnapshot, Task<Uri>>() {
    @Override
    public Task<Uri> then(@NonNull Task<UploadTask.TaskSnapshot> task) throws Exception {
        if (!task.isSuccessful()) {
            throw task.getException();
        }
        // Continue with the task to get the download URL
        return ref.getDownloadUrl();
    }
}).addOnCompleteListener(new OnCompleteListener<Uri>() {
    @Override
    public void onComplete(@NonNull Task<Uri> task) {
        if (task.isSuccessful()) {
            Uri downloadUri = task.getResult();
        } else {
            // Handle failures
            // ...
        }
    }
});
</code>```

Body:
I'm using this code below to upload an image to firebase storage but when the image is uploaded I would like to be able to recall the image using the download url. Is this possible?

ViewUserMapActivity

package uk.co.jaunt_app.jaunt;

import android.app.ProgressDialog;
import android.content.Intent;
import android.graphics.Bitmap;
import android.location.Location;
import android.net.Uri;
import android.os.Bundle;
import android.provider.MediaStore;
import android.support.annotation.NonNull;
import android.support.v4.app.FragmentActivity;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.google.android.gms.maps.CameraUpdateFactory;
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.OnMapReadyCallback;
import com.google.android.gms.maps.SupportMapFragment;
import com.google.android.gms.maps.model.BitmapDescriptorFactory;
import com.google.android.gms.maps.model.LatLng;
import com.google.android.gms.maps.model.MapStyleOptions;
import com.google.android.gms.maps.model.MarkerOptions;
import com.google.android.gms.tasks.OnFailureListener;
import com.google.android.gms.tasks.OnSuccessListener;
import com.google.firebase.storage.FirebaseStorage;
import com.google.firebase.storage.StorageReference;
import com.google.firebase.storage.UploadTask;

import java.util.UUID;

import static uk.co.jaunt_app.jaunt.R.id.MapDistance;
import static uk.co.jaunt_app.jaunt.R.id.map;

public class ViewUserMapActivity extends FragmentActivity implements OnMapReadyCallback {

    private GoogleMap mMap;
    Button HomeButt;
    TextView MapName;
    TextView MapStartLocLat;
    TextView MapStartLocLong;
    TextView MapEndLocLat;
    TextView MapEndLocLong;
    TextView mapDistance;
    Button chooseImg, uploadImg;
    ImageView imgView;
    int PICK_IMAGE_REQUEST = 111;
    Uri filePath;
    ProgressDialog pd;
    TextView imgUrl;

    FirebaseStorage storage = FirebaseStorage.getInstance();
    StorageReference storageRef = storage.getReferenceFromUrl("gs://jaunt-ddc86.appspot.com/");

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_view_user_map);
        SupportMapFragment mapFragment = (SupportMapFragment) getSupportFragmentManager()
                .findFragmentById(map);
        mapFragment.getMapAsync(this);

        HomeButt = (Button) findViewById(R.id.backHome);
        MapName = (TextView) findViewById(R.id.MapName);
        MapStartLocLat = (TextView) findViewById(R.id.MapStartLocLat);
        MapStartLocLong = (TextView) findViewById(R.id.MapStartLocLong);
        MapEndLocLat = (TextView) findViewById(R.id.MapEndLocLat);
        MapEndLocLong = (TextView) findViewById(R.id.MapEndLocLong);
        mapDistance = (TextView) findViewById(MapDistance);
        imgUrl = (TextView) findViewById(R.id.imgurl);

        Intent intent = getIntent();
        final String mapName = intent.getStringExtra("mapName");
        String mapStartLat = intent.getStringExtra("mapStartLat");
        String mapStartLong = intent.getStringExtra("mapStartLong");
        String mapEndLat = intent.getStringExtra("mapEndLat");
        String mapEndLong = intent.getStringExtra("mapEndLong");
        MapName.setText(mapName);
        MapStartLocLat.setText(mapStartLat);
        MapStartLocLong.setText(mapStartLong);
        MapEndLocLat.setText(mapEndLat);
        MapEndLocLong.setText(mapEndLong);

        chooseImg = (Button)findViewById(R.id.chooseImg);
        uploadImg = (Button)findViewById(R.id.uploadImg);
        imgView = (ImageView)findViewById(R.id.imgView);

        pd = new ProgressDialog(this);
        pd.setMessage("Uploading....");

        chooseImg.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent();
                intent.setType("image/*");
                intent.setAction(Intent.ACTION_PICK);
                startActivityForResult(Intent.createChooser(intent, "Select Image"), PICK_IMAGE_REQUEST);
            }
        });

        uploadImg.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if(filePath != null) {
                    pd.show();
                    String imageID = UUID.randomUUID().toString();
                    StorageReference childRef = storageRef.child(imageID);

                    //uploading the image
                    UploadTask uploadTask = childRef.putFile(filePath);

                    uploadTask.addOnSuccessListener(new OnSuccessListener<UploadTask.TaskSnapshot>() {
                        @Override
                        public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {
                            pd.dismiss();
                            Toast.makeText(ViewUserMapActivity.this, "Image Uploaded Successfully", Toast.LENGTH_LONG).show();
                        }

                    }).addOnFailureListener(new OnFailureListener() {
                        @Override
                        public void onFailure(@NonNull Exception e) {
                            pd.dismiss();
                            Toast.makeText(ViewUserMapActivity.this, "Upload Failed -> " + e, Toast.LENGTH_LONG).show();
                        }
                    });

                }
                else {
                    Toast.makeText(ViewUserMapActivity.this, "Select An Image", Toast.LENGTH_LONG).show();
                }
            }
        });
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);

        if (requestCode == PICK_IMAGE_REQUEST && resultCode == RESULT_OK && data != null && data.getData() != null) {
            filePath = data.getData();

            try {
                //getting image from gallery
                Bitmap bitmap = MediaStore.Images.Media.getBitmap(getContentResolver(), filePath);
                //Setting image to ImageView
                imgView.setImageBitmap(bitmap);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }

    }

    @Override
    public void onMapReady(GoogleMap googleMap) {
        mMap = googleMap;
        googleMap.setMapStyle(MapStyleOptions.loadRawResourceStyle(this, R.raw.style_json));

        String mapstartlat = MapStartLocLat.getText().toString().trim();
        String mapstartlong = MapStartLocLong.getText().toString().trim();
        String mapendlat = MapEndLocLat.getText().toString().trim();
        String mapendlong = MapEndLocLong.getText().toString().trim();

        double startlat = Double.valueOf(mapstartlat);
        double startlong = Double.valueOf(mapstartlong);
        double endlat = Double.valueOf(mapendlat);
        double endlong = Double.valueOf(mapendlong);

        LatLng Start = new LatLng(startlat, startlong);
        LatLng End = new LatLng(endlat, endlong);
        mMap.addMarker(new MarkerOptions().position(Start)
                .icon(BitmapDescriptorFactory.fromResource(R.drawable.mappin)));
        mMap.addMarker(new MarkerOptions().position(End)
                .icon(BitmapDescriptorFactory.fromResource(R.drawable.mappin)));
        mMap.moveCamera(CameraUpdateFactory.newLatLngZoom(End, 6 ));

        Location loc1 = new Location("");
        loc1.setLatitude(startlat);
        loc1.setLongitude(startlong);

        Location loc2 = new Location("");
        loc2.setLatitude(endlat);
        loc2.setLongitude(endlong);

        float distanceInMeters = loc1.distanceTo(loc2);
        Double value = 0.00062137;
        Double distanceValue = (distanceInMeters)*value;
        mapDistance.setText(String.format("%.1f mi", distanceValue));

        HomeButt.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(ViewUserMapActivity.this, MainActivity.class);
                startActivity(intent);
            }
        });

    }

}

Body:
From the Firebase documentation on uploading files:

You can upload local files on the device, such as photos and videos from the camera, with the putFile() method. putFile() takes a File and returns an UploadTask which you can use to manage and monitor the status of the upload.

Uri file = Uri.fromFile(new File("path/to/images/rivers.jpg"));
StorageReference riversRef = storageRef.child("images/"+file.getLastPathSegment());
uploadTask = riversRef.putFile(file);

Task<Uri> urlTask = uploadTask.continueWithTask(new Continuation<UploadTask.TaskSnapshot, Task<Uri>>() {
    @Override
    public Task<Uri> then(@NonNull Task<UploadTask.TaskSnapshot> task) throws Exception {
        if (!task.isSuccessful()) {
            throw task.getException();
        }
        // Continue with the task to get the download URL
        return ref.getDownloadUrl();
    }
}).addOnCompleteListener(new OnCompleteListener<Uri>() {
    @Override
    public void onComplete(@NonNull Task<Uri> task) {
        if (task.isSuccessful()) {
            Uri downloadUri = task.getResult();
        } else {
            // Handle failures
            // ...
        }
    }
});

ContentLicense: CC BY-SA 4.0


问:
java regex- get specific index where not have a specific word before
Im trying to add the double quote on a xml string only on specific place.

Here an example of xml content

```<code>    <opr:sec name=display>
     <opr:fld name=fieldName>Value1</opr:fld>
     <opr:fld name=someName>value2</opr:fld>
</code>```

I need to add double quote like : name="fieldName" and the field names are different each line.

The first double quote are simple using the name= that need to be before

But for the closing double quote i think to use the > sign, but need to avoid the fld at end.

How i regex a letter that don't have a specific text before

答:
You can  use capturing blocks, split your line into 3 blocks and reconstruct it from the pieces:</p>

```<code>String line = "<opr:fld name=fieldName>Value1</opr:fld>";
String regex = "(.*name=)(.*)(>.*>)";
Pattern pattern = Pattern.compile(regex);
Matcher matcher = pattern.matcher(line);
matcher.matches();
String result = matcher.group(1) + "\"" + matcher.group(2) + "\"" + matcher.group(3);
System.out.println(result);
</code>```

Body:
Im trying to add the double quote on a xml string only on specific place.

Here an example of xml content

    <opr:sec name=display>
     <opr:fld name=fieldName>Value1</opr:fld>
     <opr:fld name=someName>value2</opr:fld>

I need to add double quote like : name="fieldName" and the field names are different each line.

The first double quote are simple using the name= that need to be before

But for the closing double quote i think to use the > sign, but need to avoid the fld at end.

How i regex a letter that don't have a specific text before

Body:
You can  use capturing blocks, split your line into 3 blocks and reconstruct it from the pieces:

String line = "<opr:fld name=fieldName>Value1</opr:fld>";
String regex = "(.*name=)(.*)(>.*>)";
Pattern pattern = Pattern.compile(regex);
Matcher matcher = pattern.matcher(line);
matcher.matches();
String result = matcher.group(1) + "\"" + matcher.group(2) + "\"" + matcher.group(3);
System.out.println(result);


问:
C++ safe boolean idiom cannot compile with Visual C++ 10(2010)
Hey guys, I have derived my class from the C++ safe bool idiom class from this page : The Safe Bool Idiom by Bjorn Karlsson

```<code>class Element : public safe_bool<>
{
public:
    bool Exists() const;
    // boolean_test() is a safe_bool method
    bool boolean_test() const { return Exists(); };
};
</code>```

When I tried to use it in the if expression like below

```<code>Element ele;
...
if(ele)
</code>```

I got an error C2451: conditional expression of type 'Element' is illegal. If I try to cast it to bool like below, I got this error

```<code>Element ele;
...
if((bool)ele)
</code>```

error C2440: 'type cast' : cannot convert from 'Element' to 'bool'

This is the 1st time I am using safe bool idiom, I am not sure if this is not allowed or a bug in Visual C++ 10. Any comments? Thanks in advance!

答:
The safe bool idiom is allowed, although I typically write it like this:

```<code>class Element
{
public:
    bool Exists() const;

    /* Begin Safe Bool Idiom */

private:
    // This is a typedef for pointer to an int member of Element.
    typedef int Element::*SafeBoolType;
public:
    inline operator SafeBoolType() const
        { return Exists() ? &Element::someDataMember : 0; }
    inline bool operator!() const
        { return !Exists(); }

    /* End Safe Bool Idiom */

private:
    int someDataMember; // Pick any data member
    // ...
};
</code>```

This how I've seen it implemented. In fact, Boost implements the idiom in this manner for the smart pointer classes (using an include file).

Body:
Hey guys, I have derived my class from the C++ safe bool idiom class from this page : The Safe Bool Idiom by Bjorn Karlsson

class Element : public safe_bool<>
{
public:
    bool Exists() const;
    // boolean_test() is a safe_bool method
    bool boolean_test() const { return Exists(); };
};

When I tried to use it in the if expression like below

Element ele;
...
if(ele)

I got an error C2451: conditional expression of type 'Element' is illegal. If I try to cast it to bool like below, I got this error

Element ele;
...
if((bool)ele)

error C2440: 'type cast' : cannot convert from 'Element' to 'bool'

This is the 1st time I am using safe bool idiom, I am not sure if this is not allowed or a bug in Visual C++ 10. Any comments? Thanks in advance!

Body:
The safe bool idiom is allowed, although I typically write it like this:

class Element
{
public:
    bool Exists() const;

    /* Begin Safe Bool Idiom */

private:
    // This is a typedef for pointer to an int member of Element.
    typedef int Element::*SafeBoolType;
public:
    inline operator SafeBoolType() const
        { return Exists() ? &Element::someDataMember : 0; }
    inline bool operator!() const
        { return !Exists(); }

    /* End Safe Bool Idiom */

private:
    int someDataMember; // Pick any data member
    // ...
};

This how I've seen it implemented. In fact, Boost implements the idiom in this manner for the smart pointer classes (using an include file).


问:
How to remove one of the duplicate values that are next to each other in a list?
```<code>x1 = [5, 5]
x2 = [1, 5, 5, 2]
x3 = [5, 5, 1, 2, 5, 5]
x4 = [5, 5, 1, 5, 5, 2, 5, 5]
x5 = [5, -5]
x6 = [1, 2, 3, 4]
x7 = [5, 5, 5, 5, 5, 5]
</code>```

How do I remove one of the duplicate values that are next to each other on every list?

After all one of the duplicate values that are next to each other are removed, they should look like this:

```<code>x1 = [5]
x2 = [1, 5, 2]
x3 = [5, 1, 2, 5]
x4 = [5, 1, 5, 2, 5]
x5 = [5, -5]
x6 = [1, 2, 3, 4]
x7 = [5]
</code>```

答:
When there can be three or more values in a row and only a single value is wanted:</p>

```<code>from itertools import groupby

def remove_consecutive_duplicates(iterable):
    return [v for v, g in groupby(iterable)]
</code>```

Body:
x1 = [5, 5]
x2 = [1, 5, 5, 2]
x3 = [5, 5, 1, 2, 5, 5]
x4 = [5, 5, 1, 5, 5, 2, 5, 5]
x5 = [5, -5]
x6 = [1, 2, 3, 4]
x7 = [5, 5, 5, 5, 5, 5]

How do I remove one of the duplicate values that are next to each other on every list?

After all one of the duplicate values that are next to each other are removed, they should look like this:

x1 = [5]
x2 = [1, 5, 2]
x3 = [5, 1, 2, 5]
x4 = [5, 1, 5, 2, 5]
x5 = [5, -5]
x6 = [1, 2, 3, 4]
x7 = [5]

Body:
When there can be three or more values in a row and only a single value is wanted:

from itertools import groupby

def remove_consecutive_duplicates(iterable):
    return [v for v, g in groupby(iterable)]


问:
How to get a value from controller to view in laravel?
I have a simple input form with a text input field and a submit button. I am trying to get the value from the input field to be displayed again on the same page after the submit button is clicked. So far laravel always throws an error that the variable is undefined.

Route:

```<code>Route::get('/find/names', "FindController@get_name")->name('names');
</code>```

Controller

```<code> public function get_name(){
         $name = Input::get('name_by_user');
         return $name;
    }
</code>```

view

```<code>        <form role="form" method="GET">
                    <div class="row">
                        <div class="form-group">
                            <div class="input-group">
                                <input type="text" name="name_by_user"/>
                                <span class="input-group-btn">
                                    <button class="btn search-button" type="submit">
                                    <span aria-hidden="true">
                                    <span>Search</span>
                                    </button>
                                </span>
                                </span>
                            </div>
                        </div>
                    </div>
                </form>

  display name after submitting:  {{$name}}
</code>```

答:
You need to return the same view:

```<code>public function get_name(Request $request)
{
     return view('same.view', ['name' => $request->name]);
}
</code>```

Or you can redirect back:

```<code>return redirect()->back()->with('name', $request->name);
</code>```

And display name like using session data:

```<code>@if (session()->has('name'))
    {{ session('name') }}
@endif
</code>```

Body:
I have a simple input form with a text input field and a submit button. I am trying to get the value from the input field to be displayed again on the same page after the submit button is clicked. So far laravel always throws an error that the variable is undefined.

Route:

Route::get('/find/names', "FindController@get_name")->name('names');

Controller

 public function get_name(){
         $name = Input::get('name_by_user');
         return $name;
    }

view

        <form role="form" method="GET">

                                <input type="text" name="name_by_user"/>

                                    <button class="btn search-button" type="submit">

                                    Search
                                    </button>

                </form>

  display name after submitting:  {{$name}}

Body:
You need to return the same view:

public function get_name(Request $request)
{
     return view('same.view', ['name' => $request->name]);
}

Or you can redirect back:

return redirect()->back()->with('name', $request->name);

And display name like using session data:

@if (session()->has('name'))
    {{ session('name') }}
@endif


问:
Improve performance in Lat/Long geo location
I have two tables, Bins and Locations, the first with 3 million records, the second with 30 million. I am trying to match Bin for Location with the following code

```<code>Create Table #tbl_locations (LocationID int not null, Lat float not null, Lon float not null)
Create Table #tbl_bins (BinID int not null, MinLat float not null, MaxLat float not null, MinLon float not null, MaxLon float not null)

CREATE NONCLUSTERED INDEX [IX_tbl_locations] ON [#tbl_locations] ([Lat] ASC, [Lon] ASC)
ON [PRIMARY]
CREATE NONCLUSTERED INDEX [IX_tbl_bins1] ON [#tbl_bins] ([MinLat] ASC, [MaxLat] ASC)
ON [PRIMARY]
CREATE NONCLUSTERED INDEX [IX_tbl_bins2_ABC] ON [#tbl_bins] ([MinLon] ASC, [MaxLon] ASC)
ON [PRIMARY]

Select L.LocationID, C.BinID
From   #tbl_bins C
Inner Join #tbl_locations L
ON (L.Lat Between C.MinLat And C.MaxLat)
AND (L.Lon Between C.MinLon And C.MaxLon)
</code>```

Unfortunately the performance is extremely bad, I have already tried to index the different fields but that did not help enough. Everything still takes more than 10 minutes to run.

Any idea of how can I make this perform better? Maybe a better matching algorithm? SQL Server 2012 SP3.
BinID and LocationID already have a PRIMARY KEY CLUSTERED created on them.
When I check the Execution Plan I see that the JOIN is performed by a NESTED LOOP.

The output of STATISTICS IO is

```<code>Table '#tbl_locations_________________________________________________________________________________________________________000000000283'.
Scan count 2631070, logical reads 25575057, physical reads 0, read-ahead reads 0, lob logical reads 0, lob physical reads 0, lob read-ahead reads 0.
Table '#tbl_bins________________________________________________________________________________________________________000000000284'.
Scan count 17, logical reads 14741, physical reads 0, read-ahead reads 0, lob logical reads 0, lob physical reads 0, lob read-ahead reads 0.
</code>```

Thanks a lot!

Edit - if instead of Temp Tables I use real ones, this would be the schema exported

```<code>/****** Object:  Table [dbo].[tbl_Bins]    Script Date: 5/30/2017 3:49:05 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[tbl_Bins](
    [BinID] [int] NOT NULL,
    [MinLat] [float] NOT NULL,
    [MaxLat] [float] NOT NULL,
    [MinLon] [float] NOT NULL,
    [MaxLon] [float] NOT NULL,
 CONSTRAINT [PK_tbl_Bins] PRIMARY KEY CLUSTERED
(
    [BinID] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY]

GO
/****** Object:  Table [dbo].[tbl_Locations]    Script Date: 5/30/2017 3:49:05 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[tbl_Locations](
    [ExposureID] [int] NOT NULL,
    [Accgrpid] [int] NOT NULL,
    [LocID] [int] NOT NULL,
    [Lat] [float] NOT NULL,
    [Lon] [float] NOT NULL,
 CONSTRAINT [PK_tbl_locations] PRIMARY KEY CLUSTERED
(
    [ExposureID] ASC,
    [Accgrpid] ASC,
    [LocID] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY]

GO
/****** Object:  Index [IX_tbl_bins1]    Script Date: 5/30/2017 3:49:05 PM ******/
CREATE NONCLUSTERED INDEX [IX_tbl_bins1] ON [dbo].[tbl_Bins]
(
    [MinLat] ASC,
    [MaxLat] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
GO
/****** Object:  Index [IX_tbl_bins2_ABC]    Script Date: 5/30/2017 3:49:05 PM ******/
CREATE NONCLUSTERED INDEX [IX_tbl_bins2_ABC] ON [dbo].[tbl_Bins]
(
    [MinLon] ASC,
    [MaxLon] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
GO
/****** Object:  Index [IX_tbl_locations]    Script Date: 5/30/2017 3:49:05 PM ******/
CREATE NONCLUSTERED INDEX [IX_tbl_locations] ON [dbo].[tbl_Locations]
(
    [Lat] ASC,
    [Lon] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
GO
</code>```

答:
Create a covering index:

```<code>CREATE INDEX IX_tbl_lat_long_locations ON [#tbl_locations] (Lat, Lon, LocationID)
</code>```

Having such an index means the table doesn't need to be accessed in order to retrieve the LocationID.

Make it a CLUSTERED index if you can.

Body:
I have two tables, Bins and Locations, the first with 3 million records, the second with 30 million. I am trying to match Bin for Location with the following code

Create Table #tbl_locations (LocationID int not null, Lat float not null, Lon float not null)
Create Table #tbl_bins (BinID int not null, MinLat float not null, MaxLat float not null, MinLon float not null, MaxLon float not null)

CREATE NONCLUSTERED INDEX [IX_tbl_locations] ON [#tbl_locations] ([Lat] ASC, [Lon] ASC)
ON [PRIMARY]
CREATE NONCLUSTERED INDEX [IX_tbl_bins1] ON [#tbl_bins] ([MinLat] ASC, [MaxLat] ASC)
ON [PRIMARY]
CREATE NONCLUSTERED INDEX [IX_tbl_bins2_ABC] ON [#tbl_bins] ([MinLon] ASC, [MaxLon] ASC)
ON [PRIMARY]

Select L.LocationID, C.BinID
From   #tbl_bins C
Inner Join #tbl_locations L
ON (L.Lat Between C.MinLat And C.MaxLat)
AND (L.Lon Between C.MinLon And C.MaxLon)

Unfortunately the performance is extremely bad, I have already tried to index the different fields but that did not help enough. Everything still takes more than 10 minutes to run.

Any idea of how can I make this perform better? Maybe a better matching algorithm? SQL Server 2012 SP3.
BinID and LocationID already have a PRIMARY KEY CLUSTERED created on them.
When I check the Execution Plan I see that the JOIN is performed by a NESTED LOOP.

The output of STATISTICS IO is

Table '#tbl_locations_________________________________________________________________________________________________________000000000283'.
Scan count 2631070, logical reads 25575057, physical reads 0, read-ahead reads 0, lob logical reads 0, lob physical reads 0, lob read-ahead reads 0.
Table '#tbl_bins________________________________________________________________________________________________________000000000284'.
Scan count 17, logical reads 14741, physical reads 0, read-ahead reads 0, lob logical reads 0, lob physical reads 0, lob read-ahead reads 0.

Thanks a lot!

Edit - if instead of Temp Tables I use real ones, this would be the schema exported

/****** Object:  Table [dbo].[tbl_Bins]    Script Date: 5/30/2017 3:49:05 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[tbl_Bins](
    [BinID] [int] NOT NULL,
    [MinLat] [float] NOT NULL,
    [MaxLat] [float] NOT NULL,
    [MinLon] [float] NOT NULL,
    [MaxLon] [float] NOT NULL,
 CONSTRAINT [PK_tbl_Bins] PRIMARY KEY CLUSTERED
(
    [BinID] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY]

GO
/****** Object:  Table [dbo].[tbl_Locations]    Script Date: 5/30/2017 3:49:05 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[tbl_Locations](
    [ExposureID] [int] NOT NULL,
    [Accgrpid] [int] NOT NULL,
    [LocID] [int] NOT NULL,
    [Lat] [float] NOT NULL,
    [Lon] [float] NOT NULL,
 CONSTRAINT [PK_tbl_locations] PRIMARY KEY CLUSTERED
(
    [ExposureID] ASC,
    [Accgrpid] ASC,
    [LocID] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY]

GO
/****** Object:  Index [IX_tbl_bins1]    Script Date: 5/30/2017 3:49:05 PM ******/
CREATE NONCLUSTERED INDEX [IX_tbl_bins1] ON [dbo].[tbl_Bins]
(
    [MinLat] ASC,
    [MaxLat] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
GO
/****** Object:  Index [IX_tbl_bins2_ABC]    Script Date: 5/30/2017 3:49:05 PM ******/
CREATE NONCLUSTERED INDEX [IX_tbl_bins2_ABC] ON [dbo].[tbl_Bins]
(
    [MinLon] ASC,
    [MaxLon] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
GO
/****** Object:  Index [IX_tbl_locations]    Script Date: 5/30/2017 3:49:05 PM ******/
CREATE NONCLUSTERED INDEX [IX_tbl_locations] ON [dbo].[tbl_Locations]
(
    [Lat] ASC,
    [Lon] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
GO

Body:
Create a covering index:

CREATE INDEX IX_tbl_lat_long_locations ON [#tbl_locations] (Lat, Lon, LocationID)

Having such an index means the table doesn't need to be accessed in order to retrieve the LocationID.

Make it a CLUSTERED index if you can.


问:
Require FutureTask to be started before cancelled
In my Callable code I use signaling to notify multiple ending behaviours to another thread. The Callable objects are queued up with FutureTasks in an Executor. They may also be cancelled after being queued up.

Now, my problem is that I rely on the tasks atleast being started for my signaling to work, but it looks like the Executor just skips a task if it's been marked as canceled before it got a chance to run it.

So, is there a way to garantee that a task is always started, and always cancelled (by InterruptedException) while running.

Also, can you check if a task has not started but failed?

答: You can probably subclass FutureTask class and override its done() method to perform the signalling. According to the documentation, this method should be called even if the task has been cancelled. </p>


问:
Divide rows with date in SQL Server 2014
I have a problem with SQL. I have the following table:

```<code>declare @t table (START_DATE datetime,
                  END_DATE datetime,
                  GROSS_SALES_PRICE decimal(10,2)
                 );

insert into @t
values ('2014-08-06 00:00:00.000', '2014-10-06 23:59:59.000', 29.99),
       ('2014-09-06 00:00:00.000', '2014-09-09 23:59:59.000', 32.99),
       ('2014-09-10 00:00:00.000', '2014-09-30 23:59:59.000', 32.99),
       ('2014-10-07 00:00:00.000', '2049-12-31 23:59:59.000', 34.99)
</code>```

I would like to separate the dates which overlaps. For example I have in the first row START_DATE 2014-08-06 and END_DATE 2014-10-06. We can see that the dates from the second and the third row are inside this period of time from first row.

So I would like to separate them as follows:

```<code>declare @t2 table (START_DATE datetime,
                   END_DATE datetime,
                   GROSS_SALES_PRICE decimal(10,2)
                  );

insert into @t2
values ('2014-08-06 00:00:00.000', '2014-09-05 23:59:59.000', 29.99),
       ('2014-09-06 00:00:00.000', '2014-09-09 23:59:59.000', 32.99),
       ('2014-09-10 00:00:00.000', '2014-09-30 23:59:59.000', 32.99),
       ('2014-10-01 00:00:00.000', '2014-10-06 23:59:59.000', 29.99),
       ('2014-10-07 00:00:00.000', '2049-12-31 23:59:59.000', 34.99)
</code>```

So the second and the third rows remained unchanged. The first row should have new END_DATE. We also have new row. The GROSS_SALES_PRICE should remain as it is in internal period. Thanks for help. I am using SQL Server 2014

答:
Note: following solution comes with few assumptions

[1] It's using LEAD function => SQL2012+

[2] All DATETIME columns are mandatory => NOT NULL

[3] All DATETIME values (across both columns) are unique.

```<code>select y.*
from (
    select t.ID, x.DT AS NEW_START_DATE, DATEADD(MILLISECOND, -3, LEAD(x.DT) OVER(ORDER BY x.DT ASC)) AS NEW_END_DATE
    from @t as t
    outer apply (
        select t.START_DATE, 1
        union all
        select t.END_DATE, 2
    ) as x(DT, [TYPE])
) as y
where y.NEW_END_DATE IS NOT NULL
order by y.NEW_START_DATE
</code>```

Body:
I have a problem with SQL. I have the following table:

declare @t table (START_DATE datetime,
                  END_DATE datetime,
                  GROSS_SALES_PRICE decimal(10,2)
                 );

insert into @t
values ('2014-08-06 00:00:00.000', '2014-10-06 23:59:59.000', 29.99),
       ('2014-09-06 00:00:00.000', '2014-09-09 23:59:59.000', 32.99),
       ('2014-09-10 00:00:00.000', '2014-09-30 23:59:59.000', 32.99),
       ('2014-10-07 00:00:00.000', '2049-12-31 23:59:59.000', 34.99)

I would like to separate the dates which overlaps. For example I have in the first row START_DATE 2014-08-06 and END_DATE 2014-10-06. We can see that the dates from the second and the third row are inside this period of time from first row.

So I would like to separate them as follows:

declare @t2 table (START_DATE datetime,
                   END_DATE datetime,
                   GROSS_SALES_PRICE decimal(10,2)
                  );

insert into @t2
values ('2014-08-06 00:00:00.000', '2014-09-05 23:59:59.000', 29.99),
       ('2014-09-06 00:00:00.000', '2014-09-09 23:59:59.000', 32.99),
       ('2014-09-10 00:00:00.000', '2014-09-30 23:59:59.000', 32.99),
       ('2014-10-01 00:00:00.000', '2014-10-06 23:59:59.000', 29.99),
       ('2014-10-07 00:00:00.000', '2049-12-31 23:59:59.000', 34.99)

So the second and the third rows remained unchanged. The first row should have new END_DATE. We also have new row. The GROSS_SALES_PRICE should remain as it is in internal period. Thanks for help. I am using SQL Server 2014

Body:
Note: following solution comes with few assumptions

[1] It's using LEAD function => SQL2012+

[2] All DATETIME columns are mandatory => NOT NULL

[3] All DATETIME values (across both columns) are unique.

select y.*
from (
    select t.ID, x.DT AS NEW_START_DATE, DATEADD(MILLISECOND, -3, LEAD(x.DT) OVER(ORDER BY x.DT ASC)) AS NEW_END_DATE
    from @t as t
    outer apply (
        select t.START_DATE, 1
        union all
        select t.END_DATE, 2
    ) as x(DT, [TYPE])
) as y
where y.NEW_END_DATE IS NOT NULL
order by y.NEW_START_DATE