问:
Stop the navigation bar from refreshing - Umbraco
I couldn't find anything regarding my issue so I decided to post one myself.

I am using a navigation bar that has dropdown menu's. Whenever I open the dropdown and navigate to one of those pages, the navigation refreshes and closes the dropdown menu. The dropdown menu needs to stay open when I go over to one of the pages, I tried Model.Content.AncestorOrSelf().Descendants("document") to try and keep the navigation bar from refreshing but that doesn't seem to work (as people said).

Here's my menu structure:

Everything underneath "Hulp per browser" is in a dropdown and will disappear when I click on "Hulp per browser" again.

Here is my code:

```<code>@inherits Umbraco.Web.Mvc.UmbracoTemplatePage
<div class="col-sm-3">
    <div class="NavDigiCampuz">
        <h3>Helpcentrum</h3>
        <li class="NoBullet"><a class="NormalA" href="https://digicampuz.nl/">Terug naar digicampuz</a></li><br>
            <ul class="nav nav-list tree">
                @{
                    var documentRootNodeId = Model.Content.GetPropertyValue("documentRoot", true); // Fetch recursive document root id.
                    var selection = Umbraco.TypedContent(documentRootNodeId).Children.Where("Visible"); // Select all nodes below the document root.
                }

                @foreach(var item in Model.Content.AncestorOrSelf(2).Descendants("document").ToList()){
                    foreach (var ItemChild in @item.Children("categorieMenu")){
                        if(ItemChild.Children.Any())
                        {
                        <li class="MenuItems"><p>@ItemChild.Name</p></li>
                            foreach (var Subitem in @ItemChild.Children){
                                if (Subitem.Children("hoofdstuk").Any())
                                {
                                    <li class="item">
                                        @if(Subitem.GetPropertyValue("hoofdstukIcoon") != "") {
                                            <a class="NormalA aNav" href="#"><i class="fa fa-@(Subitem.GetPropertyValue("hoofdstukIcoon")) fa-fw"></i> @Subitem.Name <i id="Arrow" class="fa fa-arrow-right" style="font-size:10px;" aria-hidden="true"></i></a>
                                        }else{
                                            <a class="NormalA aNav" href="#">@Subitem.Name <i id ="Arrow" class="fa fa-arrow-right" style="font-size:10px;" aria-hidden="true"></i></a>
                                        }
                                        @foreach (var Finalitem in @Subitem.Children){
                                        <ul class="submenu">
                                            @if(Finalitem.GetPropertyValue("hoofdstukIcoon") != "") {
                                            <br><li><a class="NormalA aNav" href="@Finalitem.Url"><i class="fa fa-@(Finalitem.GetPropertyValue("hoofdstukIcoon")) fa-fw"></i>@Finalitem.Name </a></li>
                                            }else{
                                                <br><li><a class="NormalA aNav" href="@Finalitem.Url">@Finalitem.Name</a></li><br>
                                            }
                                        </ul>
                                        }
                                    </li>
                                    }else
                                        {
                                            if(Subitem.GetPropertyValue("hoofdstukIcoon") != "") {
                                                <li><a class="NormalA aNav" href="@Subitem.Url"><i class="fa fa-@(Subitem.GetPropertyValue("hoofdstukIcoon")) fa-fw"></i> @Subitem.Name</a></li>
                                            }else{
                                                <li><a class="NormalA aNav" href="@Subitem.Url">@Subitem.Name</a></li>
                                            }
                                    }
                                }
                            }
                        }
                    }
            </ul>
    </div>
</div>

<script>
    $(".item").click(function(){
        $(this).children(".submenu").toggle(); //it will display or hide your submenu when clicking the item.
    });
</script>

<style>
    .submenu{
    display: none;
    list-style:none;
    }
</style>
</code>```

I do plan on removing the script and style from the page when everything works.

答:
First thing you have several issues in the code:

Remove the Where to filter Children and keep it like var selection = Umbraco.TypedContent(documentRootNodeId).Children("Visible");

Cast your hoofdstukIcoon to string Subitem.GetPropertyValue<string>("hoofdstukIcoon")

The first
 should be in your nav-list, not outside.

You shouldn't put
 between your list items, if you want margins use css.

Now we'll focus on your issue with the submenus. What you are doing with your javascript is just using the display property to hide or show your submenu but when the page is rendered, Razor has no idea if that should be hidden or not. To solve this you have to create a new class like .visible that can be used by Razor and Javascript.

Yous hould also move your
 out of your @foreach (var Finalitem in Subitem.Children) because what you are doing now is creating a new list with one item for each one.

You should also include a conditional before your submenu in case there a no children and we don't want submenu @if (Subitem.Children.Any()) {

The way of telling your submenu with Razor if it has to diplay or not is doing this:

```<code>var isVisible = Model.Content.IsDescendantOrSelf(Subitem) ? "visible" : "";
<ul class="submenu @isVisible">
</code>```

So in that example your submenu will show if the current page is this Subitem or one of its children.

And your JS script would become this:

```<code>$(".item").click(function () {
        $(this).children(".submenu").toggleClass('visible'); //it will display or hide your submenu when clicking the item.
});
</code>```

And your CSS this:

```<code><style>
    .submenu {
        display: none;
        list-style: none;
    }

    .submenu.visible {
        display: block;
    }
</style>
</code>```

Body:
I couldn't find anything regarding my issue so I decided to post one myself.

I am using a navigation bar that has dropdown menu's. Whenever I open the dropdown and navigate to one of those pages, the navigation refreshes and closes the dropdown menu. The dropdown menu needs to stay open when I go over to one of the pages, I tried Model.Content.AncestorOrSelf().Descendants("document") to try and keep the navigation bar from refreshing but that doesn't seem to work (as people said).

Here's my menu structure:

Everything underneath "Hulp per browser" is in a dropdown and will disappear when I click on "Hulp per browser" again.

Here is my code:

@inherits Umbraco.Web.Mvc.UmbracoTemplatePage

Helpcentrum

Terug naar digicampuz

                @{
                    var documentRootNodeId = Model.Content.GetPropertyValue("documentRoot", true); // Fetch recursive document root id.
                    var selection = Umbraco.TypedContent(documentRootNodeId).Children.Where("Visible"); // Select all nodes below the document root.
                }

                @foreach(var item in Model.Content.AncestorOrSelf(2).Descendants("document").ToList()){
                    foreach (var ItemChild in @item.Children("categorieMenu")){
                        if(ItemChild.Children.Any())
                        {

@ItemChild.Name

                            foreach (var Subitem in @ItemChild.Children){
                                if (Subitem.Children("hoofdstuk").Any())
                                {

                                        @if(Subitem.GetPropertyValue("hoofdstukIcoon") != "") {
                                             @Subitem.Name
                                        }else{
                                            @Subitem.Name
                                        }
                                        @foreach (var Finalitem in @Subitem.Children){

                                            @if(Finalitem.GetPropertyValue("hoofdstukIcoon") != "") {

@Finalitem.Name

                                            }else{

@Finalitem.Name

                                            }

                                        }

                                    }else
                                        {
                                            if(Subitem.GetPropertyValue("hoofdstukIcoon") != "") {

 @Subitem.Name

                                            }else{

@Subitem.Name

                                            }
                                    }
                                }
                            }
                        }
                    }

I do plan on removing the script and style from the page when everything works.

Body:
First thing you have several issues in the code:

Remove the Where to filter Children and keep it like var selection = Umbraco.TypedContent(documentRootNodeId).Children("Visible");

Cast your hoofdstukIcoon to string Subitem.GetPropertyValue<string>("hoofdstukIcoon")

The first <li class="noBullet"> should be in your nav-list, not outside.

You shouldn't put <br> between your list items, if you want margins use css.

Now we'll focus on your issue with the submenus. What you are doing with your javascript is just using the display property to hide or show your submenu but when the page is rendered, Razor has no idea if that should be hidden or not. To solve this you have to create a new class like .visible that can be used by Razor and Javascript.

Yous hould also move your <ul class="submenu"> out of your @foreach (var Finalitem in Subitem.Children) because what you are doing now is creating a new list with one item for each one.

You should also include a conditional before your submenu in case there a no children and we don't want submenu @if (Subitem.Children.Any()) {

The way of telling your submenu with Razor if it has to diplay or not is doing this:

var isVisible = Model.Content.IsDescendantOrSelf(Subitem) ? "visible" : "";
<ul class="submenu @isVisible">

So in that example your submenu will show if the current page is this Subitem or one of its children.

And your JS script would become this:

$(".item").click(function () {
        $(this).children(".submenu").toggleClass('visible'); //it will display or hide your submenu when clicking the item.
});

And your CSS this:

<style>
    .submenu {
        display: none;
        list-style: none;
    }

    .submenu.visible {
        display: block;
    }
</style>


来源: stackexchange

问:
Highlighting Text using javascript not working
I'd like to highlight or change the background color of all p elements to yellow but it won't work.

I would also like my button be a toggle to highlight and highlight the paragraph elements. Is that possible? Help would be appreciated!

```<code> <html>
<head>
  <script type="text/javascript" src="task2.js"></script>
  <style>
  #poem {
    padding: 10px;
    margin-bottom: 10px;
    color: blue;
    font-size: 1.25em;
    font-family: sans-serif;
    background-color: silver;
    border: 1px dashed black;
    width: 30%;
  }
  </style>
</head>
<body>
<div id="poem">
<h2> How Many, How Much  </h2>
<h4> by Shel Silverstein </h4>
<p> How many slams in an old screen door? </p>
<p> Depends how loud you shut it.</p>
<p> How many slices in a bread?</p>
<p> Depends how thin you cut it.</p>
<p> How much good inside a day? </p>
<p> Depends how good you live 'em. </p>
<p> How much love inside a friend? </p>
<p> Depends how much you give 'em. </p>
</div>

<button id="yellow">Click to Highlight </button>
</body>
</html>
</code>```

here is my external js file

```<code>window.onload = function()
{
  document.getElementById("yellow").addEventListener("click", makeYellow);
}

function makeYellow() {
var paragraph = document.getElementsbyTagName("p");
paragraph.style.color ="yellow";
}
</code>```

答:
You can use querySelector and querySelectorAll.
I've attached a JSFiddle to see with 2 options - one iterates through the paragraph

```<code>var paragraph = document.querySelectorAll("p");
    paragraph.forEach(p => {
      p.style.color ="yellow";
    });
</code>```

and the second option simply adds a css class to the parent (#poem) and is obviously the preferred way.

```<code>var poem = document.querySelector('#poem');
    poem.classList.add('yellow'); // and of course you need to define the `.yellow {color: yellow;}` in your css.
</code>```

https://jsfiddle.net/L0dnbj0h/2/

Hope this helps.

ContentLicense: CC BY-SA 3.0

Body:
I'd like to highlight or change the background color of all p elements to yellow but it won't work.

I would also like my button be a toggle to highlight and highlight the paragraph elements. Is that possible? Help would be appreciated!

 How Many, How Much

 by Shel Silverstein

 How many slams in an old screen door?

 Depends how loud you shut it.

 How many slices in a bread?

 Depends how thin you cut it.

 How much good inside a day?

 Depends how good you live 'em.

 How much love inside a friend?

 Depends how much you give 'em.

<button id="yellow">Click to Highlight </button>

here is my external js file

window.onload = function()
{
  document.getElementById("yellow").addEventListener("click", makeYellow);
}

function makeYellow() {
var paragraph = document.getElementsbyTagName("p");
paragraph.style.color ="yellow";
}

Body:
You can use querySelector and querySelectorAll.
I've attached a JSFiddle to see with 2 options - one iterates through the paragraph

var paragraph = document.querySelectorAll("p");
    paragraph.forEach(p => {
      p.style.color ="yellow";
    });

and the second option simply adds a css class to the parent (#poem) and is obviously the preferred way.

var poem = document.querySelector('#poem');
    poem.classList.add('yellow'); // and of course you need to define the `.yellow {color: yellow;}` in your css.

https://jsfiddle.net/L0dnbj0h/2/

Hope this helps.


问:
Is it possible to build my own DDNS with Bind?
I know that there are many dynamic DNS service providers (including free). But I would like to build my own DDNS.

I will buy a domain name(e.g. example.com), then create a series of sub-domain(user1.example.com, user2.example.com,...). I'll deploy my own DNS(maybe with Bind) and each sub-domain need resolve to dynmaic ip(for dial-up and cable modem customers).

The customer's pc will run my client program, it will notify my server program when the ip address changed.

My question is: How to communicate between my server program and the nameserver?

答: While it is possible and BIND has a protocol for sending dynamic changes to the server, I would advise against it. There are other authoritative nameserver implementations which can serve records from SQL databases, which should integrate much better with the tools you might want to use for letting customers make updates.</p>

ContentLicense: CC BY-SA 2.5


问:
Prevent delete in Django model
I have a setup like this (simplified for this question):

```<code>class Employee(models.Model):
    name = models.CharField(name, unique=True)

class Project(models.Model):
    name = models.CharField(name, unique=True)
    employees = models.ManyToManyField(Employee)
</code>```

When an Employee is about to get deleted, I want to check whether or not he is connected to any projects. If so, deletion should be impossible.

I know about signals and how to work them. I can connect to the pre_delete signal, and make it throw an exception like ValidationError. This prevents deletion but it is not handled gracefully by forms and such.

This seems like a situation that other will have run into. I'm hoping someone can point out a more elegant solution.

答:
I would like to propose one more variation on LWN and anhdat's answers wherein we use a deleted field instead of an active field and we exclude "deleted" objects from the default queryset, so as to treat those objects as no longer present unless we specifically include them.

```<code>class SoftDeleteQuerySet(models.QuerySet):
    def delete(self):
        self.update(deleted=True)

class SoftDeleteManager(models.Manager):
    use_for_related_fields = True

    def with_deleted(self):
        return SoftDeleteQuerySet(self.model, using=self._db)

    def deleted(self):
        return self.with_deleted().filter(deleted=True)

    def get_queryset(self):
        return self.with_deleted().exclude(deleted=True)

class SoftDeleteModel(models.Model):
    """
    Sets `deleted` state of model instead of deleting it
    """
    deleted = models.NullBooleanField(editable=False)  # NullBooleanField for faster migrations with Postgres if changing existing models
    class Meta:
        abstract = True

    def delete(self):
        self.deleted = True
        self.save()

    objects = SoftDeleteManager()

class Employee(SoftDeleteModel):
    ...
</code>```

Usage:

```<code>Employee.objects.all()           # will only return objects that haven't been 'deleted'
Employee.objects.with_deleted()  # gives you all, including deleted
Employee.objects.deleted()       # gives you only deleted objects
</code>```

As stated in anhdat's answer, make sure to set the on_delete property on ForeignKeys on your model to avoid cascade behavior, e.g.

```<code>class Employee(SoftDeleteModel):
    latest_project = models.ForeignKey(Project, on_delete=models.PROTECT)
</code>```

Note:

Similar functionality is included in django-model-utils's SoftDeletableModel as I just discovered. Worth checking out. Comes with some other handy things.

ContentLicense: CC BY-SA 4.0

Title: Prevent delete in Django model

Body:
I have a setup like this (simplified for this question):

class Employee(models.Model):
    name = models.CharField(name, unique=True)

class Project(models.Model):
    name = models.CharField(name, unique=True)
    employees = models.ManyToManyField(Employee)

When an Employee is about to get deleted, I want to check whether or not he is connected to any projects. If so, deletion should be impossible.

I know about signals and how to work them. I can connect to the pre_delete signal, and make it throw an exception like ValidationError. This prevents deletion but it is not handled gracefully by forms and such.

This seems like a situation that other will have run into. I'm hoping someone can point out a more elegant solution.

Body:
I would like to propose one more variation on LWN and anhdat's answers wherein we use a deleted field instead of an active field and we exclude "deleted" objects from the default queryset, so as to treat those objects as no longer present unless we specifically include them.

class SoftDeleteQuerySet(models.QuerySet):
    def delete(self):
        self.update(deleted=True)

class SoftDeleteManager(models.Manager):
    use_for_related_fields = True

    def with_deleted(self):
        return SoftDeleteQuerySet(self.model, using=self._db)

    def deleted(self):
        return self.with_deleted().filter(deleted=True)

    def get_queryset(self):
        return self.with_deleted().exclude(deleted=True)

class SoftDeleteModel(models.Model):
    """
    Sets `deleted` state of model instead of deleting it
    """
    deleted = models.NullBooleanField(editable=False)  # NullBooleanField for faster migrations with Postgres if changing existing models
    class Meta:
        abstract = True

    def delete(self):
        self.deleted = True
        self.save()

    objects = SoftDeleteManager()

class Employee(SoftDeleteModel):
    ...

Usage:

Employee.objects.all()           # will only return objects that haven't been 'deleted'
Employee.objects.with_deleted()  # gives you all, including deleted
Employee.objects.deleted()       # gives you only deleted objects

As stated in anhdat's answer, make sure to set the on_delete property on ForeignKeys on your model to avoid cascade behavior, e.g.

class Employee(SoftDeleteModel):
    latest_project = models.ForeignKey(Project, on_delete=models.PROTECT)

Note:

Similar functionality is included in django-model-utils's SoftDeletableModel as I just discovered. Worth checking out. Comes with some other handy things.


问:
Iferror/Index/Match formula that was formerly working now returns all False results despite values existing on target sheet
I wrote a macro some time ago to search for values from one spreadsheet (Data) on another spreadsheet (Sheet1), then pull the value from the cell 2 columns to the left of where the result was found on Sheet1. It was working great, but something seems to have changed(???) and it's now returning all "False" results, despite the fact that the values certainly exist in both spreadsheets.

It searches for the values in Column C on the first worksheet on the second sheet (always called Sheet1)

I can provide the spreadsheets in question for any testing.
My annotated code is below, any help would be greatly appreciated:

```<code>Sub GroupFileNameFix()
'
' GroupFileNameFix Macro

'define variable types
Dim strFormula As Variant
Dim LastRow As Long

'on Data sheet
With ActiveSheet
' determines last row on spreadsheet and saves value to variable "LastRow"
    LastRow = .Cells(.Rows.Count, "A").End(xlUp).Row
   'sets variable "strFormula" as what we want to autofill, grabbing group filenames
strFormula = "=IFERROR(INDEX(Sheet1!RC[-3],(MATCH(RC[1],Sheet1!C[-1],0))),""False"")"
'inserts column "GroupFileName" as column D
Columns("D:D").Select
Selection.Insert Shift:=xlToRight, CopyOrigin:=xlFormatFromLeftOrAbove
Range("D1").Select
ActiveCell.FormulaR1C1 = "GroupFileName"
Columns("D:D").EntireColumn.AutoFit
' Fills cell D2 and then autofills column D to end of spreadsheet
Range("D2:D2").Select
.Range("D2:D2").Formula = strFormula
.Range("D2:D" & LastRow).FillDown
End With
'Commit formula to text and replace "png" with "jpg"
Columns("D:D").Select
Selection.Copy
Selection.PasteSpecial Paste:=xlPasteValues, Operation:=xlNone, SkipBlanks _
    :=False, Transpose:=False
Selection.Replace What:="png", Replacement:="jpg", LookAt:=xlPart, _
    SearchOrder:=xlByRows, MatchCase:=False, SearchFormat:=False, _
    ReplaceFormat:=False

End Sub
</code>```

答:
Wow, so this ended up being a lot simpler than I was making it. I got caught up in trying to automate this with a macro, when a simple paste formula & autofill workflow is just as easy. The formula below works perfectly. </p>

<p>=IFERROR(INDEX(Sheet1!A$2:A$2000,(MATCH($C2,Sheet1!C$2:C$2000,0))),"False")</p>

Body:
I wrote a macro some time ago to search for values from one spreadsheet (Data) on another spreadsheet (Sheet1), then pull the value from the cell 2 columns to the left of where the result was found on Sheet1. It was working great, but something seems to have changed(???) and it's now returning all "False" results, despite the fact that the values certainly exist in both spreadsheets.

It searches for the values in Column C on the first worksheet on the second sheet (always called Sheet1)

I can provide the spreadsheets in question for any testing.
My annotated code is below, any help would be greatly appreciated:

Sub GroupFileNameFix()
'
' GroupFileNameFix Macro

'define variable types
Dim strFormula As Variant
Dim LastRow As Long

'on Data sheet
With ActiveSheet
' determines last row on spreadsheet and saves value to variable "LastRow"
    LastRow = .Cells(.Rows.Count, "A").End(xlUp).Row
   'sets variable "strFormula" as what we want to autofill, grabbing group filenames
strFormula = "=IFERROR(INDEX(Sheet1!RC[-3],(MATCH(RC[1],Sheet1!C[-1],0))),""False"")"
'inserts column "GroupFileName" as column D
Columns("D:D").Select
Selection.Insert Shift:=xlToRight, CopyOrigin:=xlFormatFromLeftOrAbove
Range("D1").Select
ActiveCell.FormulaR1C1 = "GroupFileName"
Columns("D:D").EntireColumn.AutoFit
' Fills cell D2 and then autofills column D to end of spreadsheet
Range("D2:D2").Select
.Range("D2:D2").Formula = strFormula
.Range("D2:D" & LastRow).FillDown
End With
'Commit formula to text and replace "png" with "jpg"
Columns("D:D").Select
Selection.Copy
Selection.PasteSpecial Paste:=xlPasteValues, Operation:=xlNone, SkipBlanks _
    :=False, Transpose:=False
Selection.Replace What:="png", Replacement:="jpg", LookAt:=xlPart, _
    SearchOrder:=xlByRows, MatchCase:=False, SearchFormat:=False, _
    ReplaceFormat:=False

End Sub

Body:
Wow, so this ended up being a lot simpler than I was making it. I got caught up in trying to automate this with a macro, when a simple paste formula & autofill workflow is just as easy. The formula below works perfectly.

=IFERROR(INDEX(Sheet1!A$2:A$2000,(MATCH($C2,Sheet1!C$2:C$2000,0))),"False")


问:
Selenium - Exception while executing selenium.stop()
I am using Selenium for web application testing. After having finished all the testing, when the command "selenium.stop()" is executed I get the following exception:

```<code>java.net.ConnectException: Connection refused: connect
        at java.net.PlainSocketImpl.socketConnect(Native Method)
        at java.net.PlainSocketImpl.doConnect(PlainSocketImpl.java:333)
        at java.net.PlainSocketImpl.connectToAddress(PlainSocketImpl.java:195)
        at java.net.PlainSocketImpl.connect(PlainSocketImpl.java:182)
        at java.net.SocksSocketImpl.connect(SocksSocketImpl.java:366)
        at java.net.Socket.connect(Socket.java:519)
        at java.net.Socket.connect(Socket.java:469)
        at sun.net.NetworkClient.doConnect(NetworkClient.java:163)
        at sun.net.www.http.HttpClient.openServer(HttpClient.java:394)
        at sun.net.www.http.HttpClient.openServer(HttpClient.java:529)
        at sun.net.www.http.HttpClient.parseHTTPHeader(HttpClient.java:760)
        at sun.net.www.http.HttpClient.parseHTTP(HttpClient.java:632)
        at sun.net.www.protocol.http.HttpURLConnection.getInputStream(HttpURLConnection.java:1049)
        at java.net.HttpURLConnection.getResponseCode(HttpURLConnection.java:373)
        at com.thoughtworks.selenium.HttpCommandProcessor.getResponseCode(HttpCommandProcessor.java:134)
        at com.thoughtworks.selenium.HttpCommandProcessor.getCommandResponseAsString(HttpCommandProcessor.java:154)
        at com.thoughtworks.selenium.HttpCommandProcessor.executeCommandOnServlet(HttpCommandProcessor.java:97)
        at com.thoughtworks.selenium.HttpCommandProcessor.doCommand(HttpCommandProcessor.java:79)
        at com.thoughtworks.selenium.HttpCommandProcessor.stop(HttpCommandProcessor.java:242)
        at com.thoughtworks.selenium.DefaultSelenium.stop(DefaultSelenium.java:111)
        at seleniumproject.orkut.tearDown(orkut.java:54)
        at junit.framework.TestCase.runBare(TestCase.java:140)
        at com.thoughtworks.selenium.SeleneseTestCase.runBare(SeleneseTestCase.java:212)
        at junit.framework.TestResult$1.protect(TestResult.java:110)
E
        at junit.framework.TestResult.runProtected(TestResult.java:128)
Time: 63.453

There was 1 error:
1) testOrkut(seleniumproject.orkut)java.lang.UnsupportedOperationException: Catch body broken: IOException from cmd=testComplete -> java.net.ConnectException: Connection refused: connect
        at com.thoughtworks.selenium.HttpCommandProcessor.executeCommandOnServlet(HttpCommandProcessor.java:100)
        at com.thoughtworks.selenium.HttpCommandProcessor.doCommand(HttpCommandProcessor.java:79)
        at com.thoughtworks.selenium.HttpCommandProcessor.stop(HttpCommandProcessor.java:242)
        at com.thoughtworks.selenium.DefaultSelenium.stop(DefaultSelenium.java:111)
        at seleniumproject.orkut.tearDown(orkut.java:54)
        at com.thoughtworks.selenium.SeleneseTestCase.runBare(SeleneseTestCase.java:212)
        at seleniumproject.orkut.main(orkut.java:57)
Caused by: java.net.ConnectException: Connection refused: connect
        at java.net.PlainSocketImpl.socketConnect(Native Method)
        at java.net.PlainSocketImpl.doConnect(PlainSocketImpl.java:333)
        at java.net.PlainSocketImpl.connectToAddress(PlainSocketImpl.java:195)
        at java.net.PlainSocketImpl.connect(PlainSocketImpl.java:182)
        at junit.framework.TestResult.run(TestResult.java:113)
        at java.net.SocksSocketImpl.connect(SocksSocketImpl.java:366)
        at junit.framework.TestCase.run(TestCase.java:124)
        at java.net.Socket.connect(Socket.java:519)
        at junit.framework.TestSuite.runTest(TestSuite.java:232)
        at java.net.Socket.connect(Socket.java:469)
        at sun.net.NetworkClient.doConnect(NetworkClient.java:163)
        at junit.framework.TestSuite.run(TestSuite.java:227)
        at sun.net.www.http.HttpClient.openServer(HttpClient.java:394)
        at junit.textui.TestRunner.doRun(TestRunner.java:116)
        at junit.textui.TestRunner.doRun(TestRunner.java:109)
        at junit.textui.TestRunner.run(TestRunner.java:77)
        at seleniumproject.orkut.main(orkut.java:57)
        at sun.net.www.http.HttpClient.openServer(HttpClient.java:529)
        at sun.net.www.http.HttpClient.parseHTTPHeader(HttpClient.java:760)
        at sun.net.www.http.HttpClient.parseHTTP(HttpClient.java:632)
        at sun.net.www.protocol.http.HttpURLConnection.getInputStream(HttpURLConnection.java:1049)
        at java.net.HttpURLConnection.getResponseCode(HttpURLConnection.java:373)
        at com.thoughtworks.selenium.HttpCommandProcessor.getResponseCode(HttpCommandProcessor.java:134)
        at com.thoughtworks.selenium.HttpCommandProcessor.getCommandResponseAsString(HttpCommandProcessor.java:154)
        at com.thoughtworks.selenium.HttpCommandProcessor.executeCommandOnServlet(HttpCommandProcessor.java:97)
        ... 16 more
</code>```

Here's is code which is executing the stop() command

```<code>public class orkut extends SeleneseTestCase {
public void setUp() throws Exception {
    setUp("https://www.google.com/");
}

    public void testOrkut() throws Exception {
              Parser parser = new Parser();
              try {
                  .......
                  .......
                  .......
              }catch(Exception ex) {
              }finally {
                  parser.closeConnection();
                  selenium.shutDownSeleniumServer();
              }
    }

     public static Test suite() {
    return new TestSuite(orkut.class);
}
public void tearDown(){
    selenium.stop();
}
public static void main(String args[]) {
    junit.textui.TestRunner.run(suite());
}

}
</code>```

答: I was getting the same error. I cleared my jar files and re-added them and the exception was gone.</p>

Body:
I am using Selenium for web application testing. After having finished all the testing, when the command "selenium.stop()" is executed I get the following exception:

java.net.ConnectException: Connection refused: connect
        at java.net.PlainSocketImpl.socketConnect(Native Method)
        at java.net.PlainSocketImpl.doConnect(PlainSocketImpl.java:333)
        at java.net.PlainSocketImpl.connectToAddress(PlainSocketImpl.java:195)
        at java.net.PlainSocketImpl.connect(PlainSocketImpl.java:182)
        at java.net.SocksSocketImpl.connect(SocksSocketImpl.java:366)
        at java.net.Socket.connect(Socket.java:519)
        at java.net.Socket.connect(Socket.java:469)
        at sun.net.NetworkClient.doConnect(NetworkClient.java:163)
        at sun.net.www.http.HttpClient.openServer(HttpClient.java:394)
        at sun.net.www.http.HttpClient.openServer(HttpClient.java:529)
        at sun.net.www.http.HttpClient.parseHTTPHeader(HttpClient.java:760)
        at sun.net.www.http.HttpClient.parseHTTP(HttpClient.java:632)
        at sun.net.www.protocol.http.HttpURLConnection.getInputStream(HttpURLConnection.java:1049)
        at java.net.HttpURLConnection.getResponseCode(HttpURLConnection.java:373)
        at com.thoughtworks.selenium.HttpCommandProcessor.getResponseCode(HttpCommandProcessor.java:134)
        at com.thoughtworks.selenium.HttpCommandProcessor.getCommandResponseAsString(HttpCommandProcessor.java:154)
        at com.thoughtworks.selenium.HttpCommandProcessor.executeCommandOnServlet(HttpCommandProcessor.java:97)
        at com.thoughtworks.selenium.HttpCommandProcessor.doCommand(HttpCommandProcessor.java:79)
        at com.thoughtworks.selenium.HttpCommandProcessor.stop(HttpCommandProcessor.java:242)
        at com.thoughtworks.selenium.DefaultSelenium.stop(DefaultSelenium.java:111)
        at seleniumproject.orkut.tearDown(orkut.java:54)
        at junit.framework.TestCase.runBare(TestCase.java:140)
        at com.thoughtworks.selenium.SeleneseTestCase.runBare(SeleneseTestCase.java:212)
        at junit.framework.TestResult$1.protect(TestResult.java:110)
E
        at junit.framework.TestResult.runProtected(TestResult.java:128)
Time: 63.453

There was 1 error:
1) testOrkut(seleniumproject.orkut)java.lang.UnsupportedOperationException: Catch body broken: IOException from cmd=testComplete -> java.net.ConnectException: Connection refused: connect
        at com.thoughtworks.selenium.HttpCommandProcessor.executeCommandOnServlet(HttpCommandProcessor.java:100)
        at com.thoughtworks.selenium.HttpCommandProcessor.doCommand(HttpCommandProcessor.java:79)
        at com.thoughtworks.selenium.HttpCommandProcessor.stop(HttpCommandProcessor.java:242)
        at com.thoughtworks.selenium.DefaultSelenium.stop(DefaultSelenium.java:111)
        at seleniumproject.orkut.tearDown(orkut.java:54)
        at com.thoughtworks.selenium.SeleneseTestCase.runBare(SeleneseTestCase.java:212)
        at seleniumproject.orkut.main(orkut.java:57)
Caused by: java.net.ConnectException: Connection refused: connect
        at java.net.PlainSocketImpl.socketConnect(Native Method)
        at java.net.PlainSocketImpl.doConnect(PlainSocketImpl.java:333)
        at java.net.PlainSocketImpl.connectToAddress(PlainSocketImpl.java:195)
        at java.net.PlainSocketImpl.connect(PlainSocketImpl.java:182)
        at junit.framework.TestResult.run(TestResult.java:113)
        at java.net.SocksSocketImpl.connect(SocksSocketImpl.java:366)
        at junit.framework.TestCase.run(TestCase.java:124)
        at java.net.Socket.connect(Socket.java:519)
        at junit.framework.TestSuite.runTest(TestSuite.java:232)
        at java.net.Socket.connect(Socket.java:469)
        at sun.net.NetworkClient.doConnect(NetworkClient.java:163)
        at junit.framework.TestSuite.run(TestSuite.java:227)
        at sun.net.www.http.HttpClient.openServer(HttpClient.java:394)
        at junit.textui.TestRunner.doRun(TestRunner.java:116)
        at junit.textui.TestRunner.doRun(TestRunner.java:109)
        at junit.textui.TestRunner.run(TestRunner.java:77)
        at seleniumproject.orkut.main(orkut.java:57)
        at sun.net.www.http.HttpClient.openServer(HttpClient.java:529)
        at sun.net.www.http.HttpClient.parseHTTPHeader(HttpClient.java:760)
        at sun.net.www.http.HttpClient.parseHTTP(HttpClient.java:632)
        at sun.net.www.protocol.http.HttpURLConnection.getInputStream(HttpURLConnection.java:1049)
        at java.net.HttpURLConnection.getResponseCode(HttpURLConnection.java:373)
        at com.thoughtworks.selenium.HttpCommandProcessor.getResponseCode(HttpCommandProcessor.java:134)
        at com.thoughtworks.selenium.HttpCommandProcessor.getCommandResponseAsString(HttpCommandProcessor.java:154)
        at com.thoughtworks.selenium.HttpCommandProcessor.executeCommandOnServlet(HttpCommandProcessor.java:97)
        ... 16 more

Here's is code which is executing the stop() command

public class orkut extends SeleneseTestCase {
public void setUp() throws Exception {
    setUp("https://www.google.com/");
}

    public void testOrkut() throws Exception {
              Parser parser = new Parser();
              try {
                  .......
                  .......
                  .......
              }catch(Exception ex) {
              }finally {
                  parser.closeConnection();
                  selenium.shutDownSeleniumServer();
              }
    }

     public static Test suite() {
    return new TestSuite(orkut.class);
}
public void tearDown(){
    selenium.stop();
}
public static void main(String args[]) {
    junit.textui.TestRunner.run(suite());
}

}


问:
Check if a given key already exists in a dictionary and increment it
How do I find out if a key in a dictionary has already been set to a non-None value?

I want to increment the value if there's already one there, or set it to 1 otherwise:

```<code>my_dict = {}

if my_dict[key] is not None:
  my_dict[key] = 1
else:
  my_dict[key] += 1
</code>```

答:
The way you are trying to do it is called LBYL (look before you leap), since you are checking conditions before trying to increment your value.

The other approach is called EAFP (easier to ask forgiveness then permission).  In that case, you would just try the operation (increment the value).  If it fails, you catch the exception and set the value to 1.  This is a slightly more Pythonic way to do it (IMO).

http://mail.python.org/pipermail/python-list/2003-May/205182.html

OwnerDisplayName: Ben

Body:
How do I find out if a key in a dictionary has already been set to a non-None value?

I want to increment the value if there's already one there, or set it to 1 otherwise:

my_dict = {}

if my_dict[key] is not None:
  my_dict[key] = 1
else:
  my_dict[key] += 1

OwnerDisplayName: cgoldberg


问:
Dynamically Displaying Text with TextView (Android)
Basically what I want to do in my Android app is use TextView to display two different pieces of text at once. So in code, I want to be able to do something like this:

```<code>    LinearLayout ll = new LinearLayout(this);
    TextView text = new TextView(this);
    text.setTextColor(0xFF000000);
    text.setGravity(Gravity.CENTER_HORIZONTAL);
    text.setTextSize(20f);
    text.setText("Text1");
    text.setTextSize(14f);
    text.setColor(0xFF0000FF);
    text.setText("\nText2");
    ll.addView(text);
</code>```

To clarify, I am trying to display a black "Text1" and a blue "Text2" at once using only a single TextView. Obviously this doesn't work out using the code above. I've considered using a second TextView but that seems like a waste of effort and memory to me. I'm sure the brilliant minds here can come up with the best solution to this.

Thank you very much in advance for your time and your assistance.

答:
It seems the problem is with:

```<code>LinearLayout.addView(text);
</code>```

You are trying to add a view to a LinearLayout, but the layout doesn't exist (in the current activity). You need to add the TextView to a Layout defined in the .xml you are using. Suppose you have a LinearLayout with id "linearlayout01" in the xml file "activity1.xml", you would do something like:

```<code>setContentView(R.layout.activity1);

// Create and adjust TextView text

...

LinearLayout layout = (LinearLayout) findViewById(R.id.linearlayout01);
layout.addView(text);
</code>```

Body:
Basically what I want to do in my Android app is use TextView to display two different pieces of text at once. So in code, I want to be able to do something like this:

    LinearLayout ll = new LinearLayout(this);
    TextView text = new TextView(this);
    text.setTextColor(0xFF000000);
    text.setGravity(Gravity.CENTER_HORIZONTAL);
    text.setTextSize(20f);
    text.setText("Text1");
    text.setTextSize(14f);
    text.setColor(0xFF0000FF);
    text.setText("\nText2");
    ll.addView(text);

To clarify, I am trying to display a black "Text1" and a blue "Text2" at once using only a single TextView. Obviously this doesn't work out using the code above. I've considered using a second TextView but that seems like a waste of effort and memory to me. I'm sure the brilliant minds here can come up with the best solution to this.

Thank you very much in advance for your time and your assistance.

Body:
It seems the problem is with:

LinearLayout.addView(text);

You are trying to add a view to a LinearLayout, but the layout doesn't exist (in the current activity). You need to add the TextView to a Layout defined in the .xml you are using. Suppose you have a LinearLayout with id "linearlayout01" in the xml file "activity1.xml", you would do something like:

setContentView(R.layout.activity1);

// Create and adjust TextView text

...

LinearLayout layout = (LinearLayout) findViewById(R.id.linearlayout01);
layout.addView(text);


问:
Python two variables are the same but python doesnt think that they are
I am making a program which has a login; it checks the input against the user's input. However, it won't accept that they have entered the correct password, even when it is correct:

```<code>for i in range(5):
    existingUsername = input("What is your user name?")
    if existingUsername in open('logins.txt').read():
        with open("logins.txt", "r") as myFile:
            for num, line in enumerate(myFile, 1):
                if existingUsername in line:
                    passwordLine = num + 1
                    passwordAttempt = input(str("What is your password?"))
                    passwordText = linecache.getline("logins.txt", passwordLine)
                    if passwordAttempt == passwordText:
                        print("That is correct")
                        quizSelection()
                        break
                    else:
                        print("That doesn't seem to match. Please try again")
</code>```

The text file it references only has Har16 and Google in it, on separate lines with Har16 at the top

答: When you run passwordText = linecache.getline("logins.txt", passwordLine), if your file has multiple lines, it may return the string with \n at the end.

Body:
I am making a program which has a login; it checks the input against the user's input. However, it won't accept that they have entered the correct password, even when it is correct:

for i in range(5):
    existingUsername = input("What is your user name?")
    if existingUsername in open('logins.txt').read():
        with open("logins.txt", "r") as myFile:
            for num, line in enumerate(myFile, 1):
                if existingUsername in line:
                    passwordLine = num + 1
                    passwordAttempt = input(str("What is your password?"))
                    passwordText = linecache.getline("logins.txt", passwordLine)
                    if passwordAttempt == passwordText:
                        print("That is correct")
                        quizSelection()
                        break
                    else:
                        print("That doesn't seem to match. Please try again")

The text file it references only has Har16 and Google in it, on separate lines with Har16 at the top


问:
Mulesoft Database Connector issue . How to connect with MS SQL from MuleSoft?
I am trying to establish connection between MuleSoft and MS SQL server. This is not working at all and connection is not getting established. The ms sql database is using windows authentication. What should be a proper connector configuration / Database Url ? I am trying to use this driver: com.microsoft.sqlserver.jdbc.SQLServerDriver and using sqljdbc42.jar. We are new to MuleSoft. Please help.</p>

答:
Check if the MS SQL default port "3306" is open in your system to talk to the DB.

I had the similar issue where we were unable to connect because the port was not open.


问:
php application suddenly slow on AWS
I'm running an old PHP (7.1) / NGINX (1.10.2) application on AWS. The application runs on AWS more than few months. Since 2 days we experiencing high latency issues. But it does not affect the whole page. Only "intensive" PHP processes seems to have problems deliver the content.

I looked up so many other related topics now but nothing was pointing me to the correct direction.

First of all: The latency is not related to networking as I get these latencies also when sending a request from the server to localhost. It doesnt seem to be related to the database as well (the website is able to connect to the RDS DB within <3ms and DB CPU ~20% and Memory free >2GB looks good). Connecting to the database and running some queries made by the webserver are also performing fine.

The Webserver itself doesnt consume so much hardware resources (CPU 10-25% and Memory free ~2GB). No cronjobs/scheduled tasks are installed on this server. More than 50% iNodes still available on the server. The network gateway is retrieving/transmitting 8-25MB/seconds. We do not monitor any kind of DoS at all.

I already checked and tried to adjust the PHP FPM settings (memory_limit, process management, children processes etc.) Nothing helped here. Deactiving/Activating OPCache doesnt really has an impact.

Even when I use an AMI from a previous installation and start a new server the same latency issue happens again. Same happens when running the application in multiple availability zones.

To see where PHP is spending time I used blackfire.io and actually its telling me it spends most of the time on mysql interactions (which is not surprisingly as the application sends a lot of dirty queries with a lot of joins etc. and its the only performance expensive thing here..). I also added some debug output to the code itself. It usually gets completed within less than 6 seconds (which is sadly the normal average we know from our search..)

The latency according to the target group is by average between 3-8 seconds but we also discover a lot of latencies where the request times out (30-60seconds).

At this point I'm even quite unsure about what to provide here. I don't want to paste every related config etc here. So please tell me what you need to be able to help here :/

php-fpm/nginx log doesn't log anything related to this issue. Same with the syslog. The only thing which can be found there is Timed out waiting for reply from 91.189.89.199:123 (ntp.ubuntu.com) but even date is still in sync.. PHP FPM slow-log (timeout set to 5sec.) is empty as well. ELB Access logs are monitoring high "backend_processing_time"s only.

Nginx actually routes requests to an S3 bucket and besides one S3 mount we do not have any huge amount of temp files or other stuff on the server.

Requests send to the internet are performing as expected. DNS seems also not to be the problem (can reach db and other services in the internet as usual).

Does anyone has ideas what could cause these latency issues? What else should/can be investigated?? I really appreciate every help or question which can point me to the correct direction.

Best Regards.

答:
TL;DR At Time of writing I wasnt really aware of the Fact that RDS has CPU Credits too

A combination of robots, some stranger requests from cloud servers requesting only our search (since few months), RDS Cpu credits and by average really too many sql queries caused this phenomenon. Turned out that Cloudwatch Metrics for a t2 medium instance shows the average of CPU utilization (20%) for each of the 2 cores (baseline performance of t2.medium + sometimes higher values 30-80%) and this kills constantly all cpu credits once you lost them all and then it's really hard to earn new credits (e.g. during night).

Title: php application suddenly slow on AWS


问:
perl replace with %d
I am a newbie to Perl. I am trying to replace a string with '-S%d' string.
But in the output I see -S0 instead of -S%d. How to deal with that?
Code kind of looks like this:

```<code>$test =~ s/-S1234/-S%d/;
</code>```

For further clarification -

```<code>$test = 'This_is_StackOverflow-S11152017'
</code>```

I wish to get following output -

```<code>'This_is_StackOverflow-S%d'
</code>```

答:
The substitution works as intended, the problem is most likely with how you're printing it. You should do:

```<code>print "$test\n";
</code>```

or:

```<code>printf "%s\n", $test;
</code>```

The output you're getting would result if you did:

```<code>printf $test;
</code>```

The first argument to printf is a format string, and %d is for formatting an integer argument. With no corresponding argument, it defaults to 0.

Title: perl replace with %d

Body:
I am a newbie to Perl. I am trying to replace a string with '-S%d' string.
But in the output I see -S0 instead of -S%d. How to deal with that?
Code kind of looks like this:

$test =~ s/-S1234/-S%d/;

For further clarification -

$test = 'This_is_StackOverflow-S11152017'

I wish to get following output -

'This_is_StackOverflow-S%d'

Body:
The substitution works as intended, the problem is most likely with how you're printing it. You should do:

print "$test\n";

or:

printf "%s\n", $test;

The output you're getting would result if you did:

printf $test;

The first argument to printf is a format string, and %d is for formatting an integer argument. With no corresponding argument, it defaults to 0.


问:
Importing GCM to Firebase
After I import GCM to Firebase, what happens to my old Google Console GCM project? Does it go away?

We want to come up with a contingency plan if something goes wrong with Firebase and we need to rollback to GCM for sending out notification messages.

答: When you import a project into Firebase, all that really does is add Firebase services to that project, and you see it listed along with other Firebase-enabled projects in the Firebase console.  Nothing should change in that project that already exists at the time of import, so you should be able to safely continue whatever you were doing there.</p>

Title: Importing GCM to Firebase


问:
mysql many-to-one and group by giving unusual results
im having difficulty with the following fairly simple setup:

```<code>CREATE TABLE IF NOT EXISTS invoices (
id int(11) NOT NULL auto_increment,
PRIMARY KEY (id)
);

CREATE TABLE IF NOT EXISTS invoices_items (
id int(11) NOT NULL auto_increment,
invoice_id int(11) NOT NULL,
description text NOT NULL,
amount decimal(10,2) NOT NULL default '0.00',
PRIMARY KEY (id)
);

CREATE TABLE IF NOT EXISTS invoices_payments (
id int(11) NOT NULL auto_increment,
invoice_id int(11) NOT NULL,
amount decimal(10,2) NOT NULL default '0.00',
PRIMARY KEY (id)
);
</code>```

some data:

```<code>INSERT INTO invoices (id) VALUES (1);

INSERT INTO invoices_items (id, invoice_id, description, amount) VALUES
(1, 1, 'Item 1', '750.00'),
(2, 1, 'Item 2', '750.00'),
(3, 1, 'Item 3', '50.00'),
(4, 1, 'Item 4', '150.00');

INSERT INTO invoices_payments (id, invoice_id, amount) VALUES
(1, 1, '50.00'),
(2, 1, '1650.00');
</code>```

and the sql yielding unusual results:

```<code>select  invoices.id,
        ifnull(sum(invoices_payments.amount),0) as payments_total,
        ifnull(count(invoices_items.id),0) as item_count
from    invoices
            left join invoices_items on invoices_items.invoice_id=invoices.id
            left join invoices_payments on invoices_payments.invoice_id=invoices.id
group by invoices.id
</code>```

results in the (erroneous) output

```<code>id  payments_total  item_count
1   6800.00     8
</code>```

now, as evidenced by there being infact only four 'invoice_item' rows, i dont understand why mysql is not grouping properly.

EDIT

i know i can do something like this:

```<code>select x.*, ifnull(sum(invoices_payments.amount),0) as payments_total from (
    select  invoices.id,
            ifnull(count(invoices_items.id),0) as item_count
    from    invoices
                left join invoices_items on invoices_items.invoice_id=invoices.id
    group by invoices.id
) as x left join invoices_payments on invoices_payments.invoice_id=x.id
group by x.id
</code>```

but i want to know if im doing something wrong in the first query - i cant immediately see why the first query is giving incorrect results! :(

答:
edit:

ah, sorry - see your point now.  The reason you're getting unexpected results is that this query:

```<code>SELECT *
FROM invoices
    LEFT JOIN invoices_items ON invoices_items.invoice_id = invoices.id
    LEFT JOIN invoices_payments ON invoices_payments.invoice_id = invoices.id;
</code>```

results in this:

```<code>id  id invoice_id   description amount  id  invoice_id  amount
1    1  1            Item 1      750.00  1   1           50.00
1    1  1            Item 1      750.00  2   1           1650.00
1    2  1            Item 2      750.00  1   1           50.00
1    2  1            Item 2      750.00  2   1           1650.00
1    3  1            Item 3      50.00   1   1           50.00
1    3  1            Item 3      50.00   2   1           1650.00
1    4  1            Item 4      150.00  1   1           50.00
1    4  1            Item 4      150.00  2   1           1650.00
</code>```

As you can see you get every invoices_items record once each for every invoices_payments record.  You're going to have to grab (i.e. group) them separately.

Note that the GROUP BY clause in your initial query is redundant.

Here's what you need:

```<code>SELECT
    invoices.id,
    payments_total.payments_total,
    IFNULL(COUNT(invoices_items.id),0) AS item_count
FROM invoices
    LEFT JOIN invoices_items ON invoices.id = invoices_items.invoice_id
    LEFT JOIN (
        SELECT invoice_id,
            IFNULL(SUM(invoices_payments.amount),0) AS payments_total
            FROM invoices_payments
            GROUP BY invoice_id
        ) AS payments_total ON invoices.id  = payments_total.invoice_id
;
</code>```

Body:
im having difficulty with the following fairly simple setup:

CREATE TABLE IF NOT EXISTS invoices (
id int(11) NOT NULL auto_increment,
PRIMARY KEY (id)
);

CREATE TABLE IF NOT EXISTS invoices_items (
id int(11) NOT NULL auto_increment,
invoice_id int(11) NOT NULL,
description text NOT NULL,
amount decimal(10,2) NOT NULL default '0.00',
PRIMARY KEY (id)
);

CREATE TABLE IF NOT EXISTS invoices_payments (
id int(11) NOT NULL auto_increment,
invoice_id int(11) NOT NULL,
amount decimal(10,2) NOT NULL default '0.00',
PRIMARY KEY (id)
);

some data:

INSERT INTO invoices (id) VALUES (1);

INSERT INTO invoices_items (id, invoice_id, description, amount) VALUES
(1, 1, 'Item 1', '750.00'),
(2, 1, 'Item 2', '750.00'),
(3, 1, 'Item 3', '50.00'),
(4, 1, 'Item 4', '150.00');

INSERT INTO invoices_payments (id, invoice_id, amount) VALUES
(1, 1, '50.00'),
(2, 1, '1650.00');

and the sql yielding unusual results:

select  invoices.id,
        ifnull(sum(invoices_payments.amount),0) as payments_total,
        ifnull(count(invoices_items.id),0) as item_count
from    invoices
            left join invoices_items on invoices_items.invoice_id=invoices.id
            left join invoices_payments on invoices_payments.invoice_id=invoices.id
group by invoices.id

results in the (erroneous) output

id  payments_total  item_count
1   6800.00     8

now, as evidenced by there being infact only four 'invoice_item' rows, i dont understand why mysql is not grouping properly.

EDIT

i know i can do something like this:

select x.*, ifnull(sum(invoices_payments.amount),0) as payments_total from (
    select  invoices.id,
            ifnull(count(invoices_items.id),0) as item_count
    from    invoices
                left join invoices_items on invoices_items.invoice_id=invoices.id
    group by invoices.id
) as x left join invoices_payments on invoices_payments.invoice_id=x.id
group by x.id

but i want to know if im doing something wrong in the first query - i cant immediately see why the first query is giving incorrect results! :(

Body:
edit:

ah, sorry - see your point now.  The reason you're getting unexpected results is that this query:

SELECT *
FROM invoices
    LEFT JOIN invoices_items ON invoices_items.invoice_id = invoices.id
    LEFT JOIN invoices_payments ON invoices_payments.invoice_id = invoices.id;

results in this:

id  id invoice_id   description amount  id  invoice_id  amount
1    1  1            Item 1      750.00  1   1           50.00
1    1  1            Item 1      750.00  2   1           1650.00
1    2  1            Item 2      750.00  1   1           50.00
1    2  1            Item 2      750.00  2   1           1650.00
1    3  1            Item 3      50.00   1   1           50.00
1    3  1            Item 3      50.00   2   1           1650.00
1    4  1            Item 4      150.00  1   1           50.00
1    4  1            Item 4      150.00  2   1           1650.00

As you can see you get every invoices_items record once each for every invoices_payments record.  You're going to have to grab (i.e. group) them separately.

Note that the GROUP BY clause in your initial query is redundant.

Here's what you need:

SELECT
    invoices.id,
    payments_total.payments_total,
    IFNULL(COUNT(invoices_items.id),0) AS item_count
FROM invoices
    LEFT JOIN invoices_items ON invoices.id = invoices_items.invoice_id
    LEFT JOIN (
        SELECT invoice_id,
            IFNULL(SUM(invoices_payments.amount),0) AS payments_total
            FROM invoices_payments
            GROUP BY invoice_id
        ) AS payments_total ON invoices.id  = payments_total.invoice_id
;


问:
Angular: Date Conversion
How do I convert "2017-11-09T21:59:22.000Z" to  "01.01.2018 00:00:00" using Angular 2/4.

and vice versa : "01.01.2018 00:00:00" to  "2017-11-09T21:59:22.000Z".

I'm using primeNG calendar with showtime as the input source for the date

I basically need to convert that date format as my backend endpoint accepts a different format

答:
you can try https://momentjs.com/

it would be something like

```<code>moment('2017-11-09T21:59:22.000Z').format('DD.MM.YYYY SS:MM:HH')
</code>```

Title: Angular: Date Conversion

Body:
you can try https://momentjs.com/

it would be something like

moment('2017-11-09T21:59:22.000Z').format('DD.MM.YYYY SS:MM:HH')


问:
When will objects allocated on a thread be freed after the thread completes?
in this code

```<code>    new Thread(new Runnable() {
        @Override
        public void run() {
            byte b[] = new byte[1024*1024*1024];

            try {
                Thread.sleep(5000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            // just for testing
            b = null;

        }
    },"thread").start();
</code>```

after 5 second 1 gigabyte of memory should be free!
but it won't!

it never will!!

how can I get back memory?

答:
In Java you cannot free memory explicitly.

It depends on JVM Garbage Collector settings. There are number of parameters for GC behavior.

Some of them are different from one JVM implementation and version to another.

But, you do not need to care about it. When there is no reference to the object anymore, memory will be cleaned when GC decides that is a time for it.

In general for all variables inside the method references gone when method completed and memory can be cleaned by GC.

You can suggest GC to run like:

```<code>...
// just for testing
b = null;
System.gc();
</code>```

But it is a hint anyway. GC may run or may not.

Sometime having line like you do

```<code>b = null;
</code>```

is good not only for testing, but it is not a common case.

You may try to manipulate GC settings at JVM parameters to make GC more aggressive to avoid often Full GC runs.

There are bunch of resources on Internet as example for Oracle JVM:
Java Platform, Standard Edition HotSpot Virtual Machine Garbage Collection Tuning Guide

keep in mind: different JVM may have different parameters for GC.

Body:
in this code

    new Thread(new Runnable() {
        @Override
        public void run() {
            byte b[] = new byte[1024*1024*1024];

            try {
                Thread.sleep(5000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            // just for testing
            b = null;

        }
    },"thread").start();

after 5 second 1 gigabyte of memory should be free!
but it won't!

it never will!!

how can I get back memory?

Body:
In Java you cannot free memory explicitly.

It depends on JVM Garbage Collector settings. There are number of parameters for GC behavior.

Some of them are different from one JVM implementation and version to another.

But, you do not need to care about it. When there is no reference to the object anymore, memory will be cleaned when GC decides that is a time for it.

In general for all variables inside the method references gone when method completed and memory can be cleaned by GC.

You can suggest GC to run like:

...
// just for testing
b = null;
System.gc();

But it is a hint anyway. GC may run or may not.

Sometime having line like you do

b = null;

is good not only for testing, but it is not a common case.

You may try to manipulate GC settings at JVM parameters to make GC more aggressive to avoid often Full GC runs.

There are bunch of resources on Internet as example for Oracle JVM:
Java Platform, Standard Edition HotSpot Virtual Machine Garbage Collection Tuning Guide

keep in mind: different JVM may have different parameters for GC.


问:
Rounded table corners CSS only
I have searched and searched, but haven't been able to find a solution for my requirement.

I have a plain ol' HTML table. I want round corners for it, without using images or JS, i.e. pure CSS only. Like this:

Rounded corners for corner cells, and 1px thick border for the cells.

So far I have this:

table {
  -moz-border-radius: 5px !important;
  border-collapse: collapse !important;
  border: none !important;
}
table th,
table td {
  border: none !important
}
table th:first-child {
  -moz-border-radius: 5px 0 0 0 !important;
}
table th:last-child {
  -moz-border-radius: 0 5px 0 0 !important;
}
table tr:last-child td:first-child {
  -moz-border-radius: 0 0 0 5px !important;
}
table tr:last-child td:last-child {
  -moz-border-radius: 0 0 5px 0 !important;
}
table tr:hover td {
  background-color: #ddd !important
}
```

But that leaves me without any borders for the cells. If I add borders, they aren't rounded!

Any solutions?

答:
The selected answer is terrible. I would implement this by targeting the corner table cells and applying the corresponding border radius.

To get the top corners, set the border radius on the first and last of type of the th elements, then finish by setting the border radius on the last and first of td type on the last of type tr to get the bottom corners.

```<code>th:first-of-type {
  border-top-left-radius: 10px;
}
th:last-of-type {
  border-top-right-radius: 10px;
}
tr:last-of-type td:first-of-type {
  border-bottom-left-radius: 10px;
}
tr:last-of-type td:last-of-type {
  border-bottom-right-radius: 10px;
}
</code>```

Title: Rounded table corners CSS only

Body:
I have searched and searched, but haven't been able to find a solution for my requirement.

I have a plain ol' HTML table. I want round corners for it, without using images or JS, i.e. pure CSS only. Like this:

Rounded corners for corner cells, and 1px thick border for the cells.

So far I have this:

table {
  -moz-border-radius: 5px !important;
  border-collapse: collapse !important;
  border: none !important;
}
table th,
table td {
  border: none !important
}
table th:first-child {
  -moz-border-radius: 5px 0 0 0 !important;
}
table th:last-child {
  -moz-border-radius: 0 5px 0 0 !important;
}
table tr:last-child td:first-child {
  -moz-border-radius: 0 0 0 5px !important;
}
table tr:last-child td:last-child {
  -moz-border-radius: 0 0 5px 0 !important;
}
table tr:hover td {
  background-color: #ddd !important
}

But that leaves me without any borders for the cells. If I add borders, they aren't rounded!

Any solutions?

Body:
The selected answer is terrible. I would implement this by targeting the corner table cells and applying the corresponding border radius.

To get the top corners, set the border radius on the first and last of type of the th elements, then finish by setting the border radius on the last and first of td type on the last of type tr to get the bottom corners.

th:first-of-type {
  border-top-left-radius: 10px;
}
th:last-of-type {
  border-top-right-radius: 10px;
}
tr:last-of-type td:first-of-type {
  border-bottom-left-radius: 10px;
}
tr:last-of-type td:last-of-type {
  border-bottom-right-radius: 10px;
}


问:
REPLACE statement produces "Data truncation" error. Please advise why and how to correct it
UPDATE ASSIGNMENTS SET CBTURL = REPLACE(CBTURL, 'http://172.21.130.19/', 'https://testlpsweb.corp.mbll.ca/Content/')

The above statement produces "Data truncation" error. Please advise why and how to correct it.

Error starting at line : 1 in command - UPDATE ASSIGNMENTS SET CBTURL = REPLACE(CBTURL, 'http://172.21.130.19/', 'https://testlpsweb.corp.mbll.ca/Content/') Error at Command Line : 1 Column : 1 Error report - SQL Error: Data truncation

答:
I'm guessing that CBTURL column length is to small for resulting string of replace. Could you try to alter column to have larger lenght.
Try this query to see maximum resulst string lenght:</p>

```<code>Select Max(Len(REPLACE(CBTURL, 'http://172.21.130.19/', 'https://testlpsweb.corp.mbll.ca/Content/'))) from tablename ....
</code>```

Body:
I'm guessing that CBTURL column length is to small for resulting string of replace. Could you try to alter column to have larger lenght.
Try this query to see maximum resulst string lenght:

Select Max(Len(REPLACE(CBTURL, 'http://172.21.130.19/', 'https://testlpsweb.corp.mbll.ca/Content/'))) from tablename ....


问:
Getting compile error trying to set SetOnEditorActionListener
I'm trying to make an "Enter" softkey handler for an EditText and was getting basically the same problem as described here . . .
OnEditorActionListener code

i.e., "must implement inherited abstract method..onEditorAction.." so I tried using the solution listed in that link, but in an even more simplified form just to try to get it to compile . . .

```<code>edVacLevel.setOnEditorActionListener(new OnEditorActionListener() {
   @Override
    public boolean onEditorAction(TextView arg0, int keycode) {
    return true;
     }
  });
</code>```

... and now it flags OnEditorActionListener and says "Class must either be declared abstract or implement abstract method "
Yet looking at other examples on the web and in StackOverflow, this seems to be the canonical way to handle Enter Keys in an EditText.   So what am I doing wrong?  (Android Studio 2.2.2)

答:
Check your paraments for onEditorAction() method. They should be.
So your code should look like

```<code>@Override
 public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
     if ((event != null && (event.getKeyCode() == KeyEvent.KEYCODE_ENTER)) || (actionId == EditorInfo.IME_ACTION_DONE)) {
         //Do your stuff here
         return true;
     }
     return false;
 }
</code>```

Java is complaining because you are supposed to override the exact method name with respective parameter types.

Body:
I'm trying to make an "Enter" softkey handler for an EditText and was getting basically the same problem as described here . . .
OnEditorActionListener code

i.e., "must implement inherited abstract method..onEditorAction.." so I tried using the solution listed in that link, but in an even more simplified form just to try to get it to compile . . .

edVacLevel.setOnEditorActionListener(new OnEditorActionListener() {
   @Override
    public boolean onEditorAction(TextView arg0, int keycode) {
    return true;
     }
  });

... and now it flags OnEditorActionListener and says "Class must either be declared abstract or implement abstract method "
Yet looking at other examples on the web and in StackOverflow, this seems to be the canonical way to handle Enter Keys in an EditText.   So what am I doing wrong?  (Android Studio 2.2.2)

Body:
Check your paraments for onEditorAction() method. They should be.
So your code should look like

@Override
 public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
     if ((event != null && (event.getKeyCode() == KeyEvent.KEYCODE_ENTER)) || (actionId == EditorInfo.IME_ACTION_DONE)) {
         //Do your stuff here
         return true;
     }
     return false;
 }

Java is complaining because you are supposed to override the exact method name with respective parameter types.


问:
How to initialize values inside nested json struct in GO?
I have this struct right now

```<code>type ServiceStruct struct {
      Name     string `json:"name"`
      DataStruct struct {
          ID    string `json:"id"`
          Size  string `json:"size"`
     }
}
</code>```

But im not sure how to assign values to the elements inside this struct. Specially the DataStruct inside the ServiceStruct

答:
https://play.golang.org/p/GObadB9WyN

Example of passing/unmarshaling a JSON into your struct. This has been my primary use-case, I hope it is helpful.

```<code>package main

import (
    "fmt"
    "encoding/json"
)

type ServiceStruct struct {
    Name     string `json:"name"`
    DataStruct struct {
        ID    string `json:"id"`
        Size  string `json:"size"`
    }
}

func main() {
    x := `{
        "Name": "Fido",
        "DataStruct": {
            "ID": "Dog",
            "Size": "Small"
        }
    }`

    ex := ServiceStruct{}
    json.Unmarshal([]byte(x), &ex)

    fmt.Println(ex.Name)
}
</code>```

Body:
I have this struct right now

type ServiceStruct struct {
      Name     string `json:"name"`
      DataStruct struct {
          ID    string `json:"id"`
          Size  string `json:"size"`
     }
}

But im not sure how to assign values to the elements inside this struct. Specially the DataStruct inside the ServiceStruct

Body:
https://play.golang.org/p/GObadB9WyN

Example of passing/unmarshaling a JSON into your struct. This has been my primary use-case, I hope it is helpful.

package main

import (
    "fmt"
    "encoding/json"
)

type ServiceStruct struct {
    Name     string `json:"name"`
    DataStruct struct {
        ID    string `json:"id"`
        Size  string `json:"size"`
    }
}

func main() {
    x := `{
        "Name": "Fido",
        "DataStruct": {
            "ID": "Dog",
            "Size": "Small"
        }
    }`

    ex := ServiceStruct{}
    json.Unmarshal([]byte(x), &ex)

    fmt.Println(ex.Name)
}


问:
Get price of phone number from Twilio
I am trying to get the price of a phone number in Twilio. I have this to get the phone numbers

```<code>var localAvailableNumbers = Twilio.Rest.Api.V2010.Account.AvailablePhoneNumberCountry.LocalResource.Read("US");
</code>```

And this to get the prices

```<code>var prices = Twilio.Rest.Pricing.V1.PhoneNumber.CountryResource.Fetch("US");
</code>```

But I can't see any way to map each of the phone numbers to a price?

This is an example of the response from the phone numbers request

```<code>{
  "uri": "\/2010-04-01\/Accounts\/ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX\/AvailablePhoneNumbers\/US\/Local.json?AreaCode=510",
  "available_phone_numbers": [
    {
      "friendly_name": "(510) 564-7903",
      "phone_number": "+15105647903",
      "lata": "722",
      "rate_center": "OKLD TRNID",
      "latitude": "37.780000",
      "longitude": "-122.380000",
      "region": "CA",
      "postal_code": "94703",
      "iso_country": "US",
      "capabilities":{
        "voice": true,
        "SMS": true,
        "MMS": false
      },
      "beta": false
    }
  ]
}
</code>```

Nowhere does it tell me if this is local, mobile, toll free etc.

答:
I found the problem. For the different phone number types I need to make different queries.</p>

```<code>// Local numbers
var numbers = LocalResource.Read("US");

// Mobile numbers
var numbers = MobileResource.Read("US");
</code>```

Title: Get price of phone number from Twilio

Body:
I am trying to get the price of a phone number in Twilio. I have this to get the phone numbers

var localAvailableNumbers = Twilio.Rest.Api.V2010.Account.AvailablePhoneNumberCountry.LocalResource.Read("US");

And this to get the prices

var prices = Twilio.Rest.Pricing.V1.PhoneNumber.CountryResource.Fetch("US");

But I can't see any way to map each of the phone numbers to a price?

This is an example of the response from the phone numbers request

{
  "uri": "\/2010-04-01\/Accounts\/ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX\/AvailablePhoneNumbers\/US\/Local.json?AreaCode=510",
  "available_phone_numbers": [
    {
      "friendly_name": "(510) 564-7903",
      "phone_number": "+15105647903",
      "lata": "722",
      "rate_center": "OKLD TRNID",
      "latitude": "37.780000",
      "longitude": "-122.380000",
      "region": "CA",
      "postal_code": "94703",
      "iso_country": "US",
      "capabilities":{
        "voice": true,
        "SMS": true,
        "MMS": false
      },
      "beta": false
    }
  ]
}

Nowhere does it tell me if this is local, mobile, toll free etc.

Body:
I found the problem. For the different phone number types I need to make different queries.

// Local numbers
var numbers = LocalResource.Read("US");

// Mobile numbers
var numbers = MobileResource.Read("US");


问:
Type and non-type template parameters to use interchangeably
Is it possible in C++ to declare some class so that it would be allowed to pass integer value or type as template parameter?

Something like this:

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

template <auto I>
struct Foo {};

int main()
{
    Foo<int> foo1;
    Foo<1> foo2;
    return 0;
}
</code>```

答:
Nope, that is not possible. As a workaround, you could use std::integral_constant in order to pass values homogeneously as types.

```<code>template <typename I>
struct Foo {};

int main()
{
    Foo<int> foo1;
    Foo<std::integral_constant<int, 1>> foo2;
}
</code>```

With C++17, you can define

```<code>template <auto I>
using constant = std::integral_constant<decltype(I), I>;
</code>```

to avoid some boilerplate.

Body:
Is it possible in C++ to declare some class so that it would be allowed to pass integer value or type as template parameter?

Something like this:

#include <iostream>
using namespace std;

template <auto I>
struct Foo {};

int main()
{
    Foo<int> foo1;
    Foo<1> foo2;
    return 0;
}

Body:
Nope, that is not possible. As a workaround, you could use std::integral_constant in order to pass values homogeneously as types.

template <typename I>
struct Foo {};

int main()
{
    Foo<int> foo1;
    Foo<std::integral_constant<int, 1>> foo2;
}

With C++17, you can define

template <auto I>
using constant = std::integral_constant<decltype(I), I>;

to avoid some boilerplate.


问:
Joda-Time DateTimeZone not comparing correctly
I've been working on unit tests for a project that uses Joda-Time, and I noticed that DateTimeZone instances that should represent the same time-zone aren't returning true on equals. In particular, on unit tests like these below

// should be the same
DateTimeZone WAT = DateTimeZone.forOffsetHours(1); // GMT+01:00
DateTimeZone LAG = DateTimeZone.forID("Africa/Lagos"); // Lagos

DateTime sample = new DateTime(2017, 11, 15, 10, 50);
DateTime dtzWAT = sample.withZoneRetainFields(WAT);
DateTime dtzLAG = sample.withZoneRetainFields(LAG);

@Test public void compareZones() { assertEquals(WAT, LAG); }
@Test public void compareTimes() { assertEquals(dtzWAT, dtzLAG); }
```

<p>both tests fail even though <code>Africa/Lagos</code> and <code>GMT+01:00</code> are the same time zone, and the two <code>DateTimes</code> represent the same instant - in fact, the two tests below confirm this</p>

<pre class="lang-java prettyprint-override"><code>// both succeed
@Test public void compareStrings() {
    assertEquals(dtzWAT.toString(), dtzLAG.toString());
}

@Test public void checkSameTime() {
    assertFalse(dtzLAG.isBefore(dtzWAT));
    assertFalse(dtzWAT.isBefore(dtzLAG));
}
</code>```

Why does this happen? Why are the two time-zone instances not equivalent, and is there anyway around this? Any help would be appreciated.

答:
why does this happen

The DateTimeZones are not equal: one is called Africa/Lagos, the other is GMT+01:00. It says in the Javadoc of DateTimeZone.equals

true if equal, based on the ID and all internal rules

And for DateTime.equals:

Compares this object with the specified object for equality based on the millisecond instant, chronology and time zone.

The time zones aren't equal, so the DateTimes aren't equal.

Maybe they are effectively equal, doesn't mean they actually are.

Note that java.util.TimeZone has the hasSameRules(...) method, which is a separate notion from equality.

Body:
I've been working on unit tests for a project that uses Joda-Time, and I noticed that DateTimeZone instances that should represent the same time-zone aren't returning true on equals. In particular, on unit tests like these below

// should be the same
DateTimeZone WAT = DateTimeZone.forOffsetHours(1); // GMT+01:00
DateTimeZone LAG = DateTimeZone.forID("Africa/Lagos"); // Lagos

DateTime sample = new DateTime(2017, 11, 15, 10, 50);
DateTime dtzWAT = sample.withZoneRetainFields(WAT);
DateTime dtzLAG = sample.withZoneRetainFields(LAG);

@Test public void compareZones() { assertEquals(WAT, LAG); }
@Test public void compareTimes() { assertEquals(dtzWAT, dtzLAG); }

both tests fail even though Africa/Lagos and GMT+01:00 are the same time zone, and the two DateTimes represent the same instant - in fact, the two tests below confirm this

// both succeed
@Test public void compareStrings() {
    assertEquals(dtzWAT.toString(), dtzLAG.toString());
}

@Test public void checkSameTime() {
    assertFalse(dtzLAG.isBefore(dtzWAT));
    assertFalse(dtzWAT.isBefore(dtzLAG));
}

Why does this happen? Why are the two time-zone instances not equivalent, and is there anyway around this? Any help would be appreciated.


问:
How to use substring function in oracle in date columns which is in number format
I have a Column Called FILLD_DT in a table which has number(8) data type format. I am trying to use this column and create a new column called Derived date in my own table.

Ex: Filled Date = 20170107

Below is the query I am using and I am getting

ORA-00932: inconsistent datatypes: expected CHAR got NUMBER

```<code>(CASE WHEN PERD = 'Beginning' AND SUBSTR(FILLD_DT,5,2) IN (01,02,03) AND SUBSTR(FILLD_DT,1,4) = 2017  THEN  '20170101'
      WHEN PERD = 'Beginning' AND SUBSTR(FILLD_DT,5,2) IN (04,05,06) AND SUBSTR(FILLD_DT,1,4) = 2017  THEN '20170501'
      WHEN PERD = 'Beginning' AND SUBSTR(FILLD_DT,5,2) IN (07,08,09) AND SUBSTR(FILLD_DT,1,4) = 2017  THEN '20170701'
      WHEN PERD = 'Beginning' AND SUBSTR(FILLD_DT,5,2) IN (10,11,12) AND SUBSTR(FILLD_DT,1,4) = 2017  THEN  '20171001'
 ELSE FILLD_DT
 END ) AS DRVD_DATE
</code>```

please help me understand

below is the full query

```<code>SELECT DISTINCT
SRC_ID,
SEQ_NBR,
PROD_ID,
TYPE_CD,
FILLD_DT,
PRCSD_DT,
(CASE WHEN PERD = 'Beginning' AND SUBSTR(FILLD_DT,5,2) IN (01,02,03) AND SUBSTR(FILLD_DT,1,4) = 2017  THEN  '20170101'
 WHEN PERD = 'Beginning' AND SUBSTR(FILLD_DT,5,2) IN (04,05,06) AND SUBSTR(FILLD_DT,1,4) = 2017  THEN '20170401'
WHEN PERD = 'Beginning' AND SUBSTR(FILLD_DT,5,2) IN (07,08,09) AND SUBSTR(FILLD_DT,1,4) = 2017  THEN '20170701'
WHEN PERD = 'Beginning' AND SUBSTR(FILLD_DT,5,2) IN (10,11,12) AND SUBSTR(FILLD_DT,1,4) = 2017  THEN  '20171001'
WHEN PERD = 'middle' AND SUBSTR(FILLD_DT,5,2) IN (01,02,03) AND SUBSTR(FILLD_DT,1,4) = 2017  THEN  '20170115'
 WHEN PERD = 'middle' AND SUBSTR(FILLD_DT,5,2) IN (04,05,06) AND SUBSTR(FILLD_DT,1,4) = 2017  THEN '20170415'
WHEN PERD = 'middle' AND SUBSTR(FILLD_DT,5,2) IN (07,08,09) AND SUBSTR(FILLD_DT,1,4) = 2017  THEN '20170715'
WHEN PERD = 'middle' AND SUBSTR(FILLD_DT,5,2) IN (10,11,12) AND SUBSTR(FILLD_DT,1,4) = 2017  THEN  '20171015'
ELSE FILLD_DT
END)
FROM
SOURCE
</code>```

and I modified the query to your suggestion and I am getting the below error

[Error] Execution (8: 29): ORA-01830: date format picture ends
  before converting entire input string

```<code>SELECT DISTINCT
SRC_ID,
SEQ_NBR,
PROD_ID,
TYPE_CD,
FILLD_DT,
PRCSD_DT,
( trunc( to_date( FILLD_DT || '01', 'yyyymmdd' ), 'Q' )
 ) AS DRVD_DATE
FROM
SOURCE
WHERE
SRC_ID = 163662
</code>```

答:
Convert the number, which represents a DATE, to character before converting it to DATE.

DECLARE
    FILLD_DT        NUMBER(0008) := 20170107;
    DRVD_DATE       DATE;
BEGIN
    DBMS_OUTPUT.ENABLE(1000);
    DRVD_DATE :=
        TO_DATE
            (
            TO_CHAR(FILLD_DT)
            ,'YYYYMMDD'
            );
    DBMS_OUTPUT.PUT_LINE('Derived Date: ' || TO_CHAR(DRVD_DATE,'yyyy-mm-dd'));
END;
Not understanding what you are trying to do with "FILLD_DT || '01'".  At best that would give you a string of '2017010701' which doesn't match your DATE format string of 'YYYYMMDD'.

Body:
I have a Column Called FILLD_DT in a table which has number(8) data type format. I am trying to use this column and create a new column called Derived date in my own table.

Ex: Filled Date = 20170107

Below is the query I am using and I am getting

ORA-00932: inconsistent datatypes: expected CHAR got NUMBER

(CASE WHEN PERD = 'Beginning' AND SUBSTR(FILLD_DT,5,2) IN (01,02,03) AND SUBSTR(FILLD_DT,1,4) = 2017  THEN  '20170101'
      WHEN PERD = 'Beginning' AND SUBSTR(FILLD_DT,5,2) IN (04,05,06) AND SUBSTR(FILLD_DT,1,4) = 2017  THEN '20170501'
      WHEN PERD = 'Beginning' AND SUBSTR(FILLD_DT,5,2) IN (07,08,09) AND SUBSTR(FILLD_DT,1,4) = 2017  THEN '20170701'
      WHEN PERD = 'Beginning' AND SUBSTR(FILLD_DT,5,2) IN (10,11,12) AND SUBSTR(FILLD_DT,1,4) = 2017  THEN  '20171001'
 ELSE FILLD_DT
 END ) AS DRVD_DATE

please help me understand

below is the full query

SELECT DISTINCT
SRC_ID,
SEQ_NBR,
PROD_ID,
TYPE_CD,
FILLD_DT,
PRCSD_DT,
(CASE WHEN PERD = 'Beginning' AND SUBSTR(FILLD_DT,5,2) IN (01,02,03) AND SUBSTR(FILLD_DT,1,4) = 2017  THEN  '20170101'
 WHEN PERD = 'Beginning' AND SUBSTR(FILLD_DT,5,2) IN (04,05,06) AND SUBSTR(FILLD_DT,1,4) = 2017  THEN '20170401'
WHEN PERD = 'Beginning' AND SUBSTR(FILLD_DT,5,2) IN (07,08,09) AND SUBSTR(FILLD_DT,1,4) = 2017  THEN '20170701'
WHEN PERD = 'Beginning' AND SUBSTR(FILLD_DT,5,2) IN (10,11,12) AND SUBSTR(FILLD_DT,1,4) = 2017  THEN  '20171001'
WHEN PERD = 'middle' AND SUBSTR(FILLD_DT,5,2) IN (01,02,03) AND SUBSTR(FILLD_DT,1,4) = 2017  THEN  '20170115'
 WHEN PERD = 'middle' AND SUBSTR(FILLD_DT,5,2) IN (04,05,06) AND SUBSTR(FILLD_DT,1,4) = 2017  THEN '20170415'
WHEN PERD = 'middle' AND SUBSTR(FILLD_DT,5,2) IN (07,08,09) AND SUBSTR(FILLD_DT,1,4) = 2017  THEN '20170715'
WHEN PERD = 'middle' AND SUBSTR(FILLD_DT,5,2) IN (10,11,12) AND SUBSTR(FILLD_DT,1,4) = 2017  THEN  '20171015'
ELSE FILLD_DT
END)
FROM
SOURCE

and I modified the query to your suggestion and I am getting the below error

[Error] Execution (8: 29): ORA-01830: date format picture ends
  before converting entire input string

SELECT DISTINCT
SRC_ID,
SEQ_NBR,
PROD_ID,
TYPE_CD,
FILLD_DT,
PRCSD_DT,
( trunc( to_date( FILLD_DT || '01', 'yyyymmdd' ), 'Q' )
 ) AS DRVD_DATE
FROM
SOURCE
WHERE
SRC_ID = 163662


问:
Fix display garbage left by WPF dialog window?
In my WPF app, I have WPF windows that can open other WPF dialog windows, which I do as follows:

```<code>PickForEveryone PickForEveryoneWindow = new PickForEveryone(sSelRecipe, selMRM.sDay, selMRM.MealTypeID);
PickForEveryoneWindow.Owner = this;
PickForEveryoneWindow.ShowDialog();
</code>```

Where PickForEveryone is defined as:

```<code>public partial class PickForEveryone : Window
</code>```

and

```<code><Window x:Class="PFWb0.PickForEveryone"
 xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
 xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
 xmlns:dg="http://schemas.microsoft.com/wpf/2008/toolkit"
 ShowInTaskbar="False"
 Title="Pick Recipe For All" Height="536" Width="441"
 WindowStartupLocation="CenterOwner">
</code>```

And contains a Grid with a DataGrid and a few buttons and check boxes.

Which works fine on my development computers. However, my client keeps seeing the dialog windows leave part of their display as visual litter on top of the parent window when the dialog window closes. That is, only some of the window undraws when ShowDialog() returns.

I tried adding this.InvalidateVisual(); below the above code, but it didn't solve the problem.

I also saw a suggestion here (for another kind of WPF display problem) to call OnRender() to force a redraw, but OnRender requires a parameter of type DrawingContext, which I don't know how to get.

So, I am asking if anyone knows how to either fix the display problem in the first place, or how to recover from it by getting WPF to redraw a window.

Update: As seen in comments to suggested answers below, I still have no solution that works on my client's computers, and my workaround (of having the windows dodge each other) is no longer enough. The only thing that works is to minimize and maximize the polluted underlying window.

答:
So I have been looking for an answer to this on the MS forums, and apparently, variations of this question have been a asked for a few years now.

Sometimes, they say, the problem has to do with video drivers, of all things, although in my case, my client has recently updated his video drivers.

My impression is that Microsoft thought they designed WPF so that a developer should never need to do such a thing as force a redraw of the display, so they make no way to do so by design. Of course, when things go wrong for whatever reason, this means there is no straightforward way to do so. And the ways that seem like they might do so (such as InvalidateVisual()), don't.

But I did find one hack that does work. Well, two. The ugly one is to tell the window to minimize and return to normal. But that results in a visual animation of it doing so, which is not ideal. In my case, it also made it hide behind other open windows, requiring me to make it go topmost. But is does solve the problem, in a jarring way.

Code after ShowDialog:

```<code>    this.WindowState = WindowState.Minimized;
    this.WindowState = WindowState.Normal;
    this.Topmost = true;
</code>```

The better hack, looks a bit like this:

Code outside:

```<code>public delegate void NoArgDelegate();
</code>```

Code after ShowDialog:

```<code>    this.Dispatcher.Invoke(
    System.Windows.Threading.DispatcherPriority.Loaded,
        (NoArgDelegate)delegate {}
    );
</code>```

Presto ala kazzam!

Body:
In my WPF app, I have WPF windows that can open other WPF dialog windows, which I do as follows:

PickForEveryone PickForEveryoneWindow = new PickForEveryone(sSelRecipe, selMRM.sDay, selMRM.MealTypeID);
PickForEveryoneWindow.Owner = this;
PickForEveryoneWindow.ShowDialog();

Where PickForEveryone is defined as:

public partial class PickForEveryone : Window

and

<Window x:Class="PFWb0.PickForEveryone"
 xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
 xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
 xmlns:dg="http://schemas.microsoft.com/wpf/2008/toolkit"
 ShowInTaskbar="False"
 Title="Pick Recipe For All" Height="536" Width="441"
 WindowStartupLocation="CenterOwner">

And contains a Grid with a DataGrid and a few buttons and check boxes.

Which works fine on my development computers. However, my client keeps seeing the dialog windows leave part of their display as visual litter on top of the parent window when the dialog window closes. That is, only some of the window undraws when ShowDialog() returns.

I tried adding this.InvalidateVisual(); below the above code, but it didn't solve the problem.

I also saw a suggestion here (for another kind of WPF display problem) to call OnRender() to force a redraw, but OnRender requires a parameter of type DrawingContext, which I don't know how to get.

So, I am asking if anyone knows how to either fix the display problem in the first place, or how to recover from it by getting WPF to redraw a window.

Update: As seen in comments to suggested answers below, I still have no solution that works on my client's computers, and my workaround (of having the windows dodge each other) is no longer enough. The only thing that works is to minimize and maximize the polluted underlying window.

Body:
So I have been looking for an answer to this on the MS forums, and apparently, variations of this question have been a asked for a few years now.

Sometimes, they say, the problem has to do with video drivers, of all things, although in my case, my client has recently updated his video drivers.

My impression is that Microsoft thought they designed WPF so that a developer should never need to do such a thing as force a redraw of the display, so they make no way to do so by design. Of course, when things go wrong for whatever reason, this means there is no straightforward way to do so. And the ways that seem like they might do so (such as InvalidateVisual()), don't.

But I did find one hack that does work. Well, two. The ugly one is to tell the window to minimize and return to normal. But that results in a visual animation of it doing so, which is not ideal. In my case, it also made it hide behind other open windows, requiring me to make it go topmost. But is does solve the problem, in a jarring way.

Code after ShowDialog:

    this.WindowState = WindowState.Minimized;
    this.WindowState = WindowState.Normal;
    this.Topmost = true;

The better hack, looks a bit like this:

Code outside:

public delegate void NoArgDelegate();

Code after ShowDialog:

    this.Dispatcher.Invoke(
    System.Windows.Threading.DispatcherPriority.Loaded,
        (NoArgDelegate)delegate {}
    );

Presto ala kazzam!