问:
Offline Promise Handling in Angularfire2
As per my understanding, Angularfire2 returns a Promise < void > whenever a query runs successfully(except fetch when it returns data).

Functionality:

I have a application where when a item is saved a function is called inside which if the set query is run successfully(i.e it receives a Promise< void >) it navigates to the previous page.
It works perfectly when app is online but the app also needs to work offline. I have enabled persistence and configured service workers for the same

Issue

But when offline the code after the query returns a Promise is not called.So what should be the expected logic or behaviour during offline.

```<code>                this._itemService.setItem(item).then(()=>{
                    const message = item.name + saveMessage;
                    this.snackBar.open(message," ",{duration:2000});
                    this.location.back();

                }
</code>```

答:
```<code>           let itemPromise= this._itemService.setItem(item);

            if(navigator.onLine && itemPromise instanceof Promise){
                itemPromise.then(()=>{
                    const message = item.name + "account saved";
                    this.snackBar.open(message," ",{duration:2000});

                   ...More code
                    this.closeClicked();
                });
            }else{

                const message = item.name + "account saved";
                this.snackBar.open(message," ",{duration:2000});
                this.closeClicked();
            }
</code>```

Body:
As per my understanding, Angularfire2 returns a Promise < void > whenever a query runs successfully(except fetch when it returns data).

Functionality:

I have a application where when a item is saved a function is called inside which if the set query is run successfully(i.e it receives a Promise< void >) it navigates to the previous page.
It works perfectly when app is online but the app also needs to work offline. I have enabled persistence and configured service workers for the same

Issue

But when offline the code after the query returns a Promise is not called.So what should be the expected logic or behaviour during offline.

                this._itemService.setItem(item).then(()=>{
                    const message = item.name + saveMessage;
                    this.snackBar.open(message," ",{duration:2000});
                    this.location.back();

                }


来源: stackexchange

问:
file open dotnet core 2.1 System.IO.IOException
I'm creating a dotnet core 2.1 project when I try to open a file I get this error System.IO.IOException because it looks for the file under netcoreapp2.1

```<code>class Program
{
   static void Main(string[] args)
   {
       string path = "C:\user\name\desktop\file.txt";
       FileStream file = new FileStream(path, FileMode.Open);
   }
}
</code>```

and error is

```<code>   System.IO.IOException: The syntax of the file name, directory or volume is incorrect C:\Users\name\source\repos\app\app\bin\Debug\netcoreapp2.1\C:\user\name\Desktop\file.txt
</code>```

答:
Because slashes are not escaped, FileStream is assuming the path to be relative to the current folder.
Use literal string or escape the path.</p>

```<code>string path = @"C:\user\name\desktop\file.txt"; // Note the @ that denotes a literal string.
FileStream file = new FileStream(path, FileMode.Open);
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I'm creating a dotnet core 2.1 project when I try to open a file I get this error System.IO.IOException because it looks for the file under netcoreapp2.1

class Program
{
   static void Main(string[] args)
   {
       string path = "C:\user\name\desktop\file.txt";
       FileStream file = new FileStream(path, FileMode.Open);
   }
}

and error is

   System.IO.IOException: The syntax of the file name, directory or volume is incorrect C:\Users\name\source\repos\app\app\bin\Debug\netcoreapp2.1\C:\user\name\Desktop\file.txt

Body:
Because slashes are not escaped, FileStream is assuming the path to be relative to the current folder.
Use literal string or escape the path.

string path = @"C:\user\name\desktop\file.txt"; // Note the @ that denotes a literal string.
FileStream file = new FileStream(path, FileMode.Open);


问:
How can I detect a mouse leaving a page by moving up to the address bar?
I have created a jQuery event that pops up a dialog when a visitor is leaving a page. I am using the e.pageY to detect the mouse position. when the mouse is at Y: less than 2, the dialog pops up. the problem is, when the I scroll down through the page and decided to leave the page, the pop up does not show since the mouse is not at Y: less than 2. How can I fix that. i.e. when I leave the page and just hover over the address bar, a pop up appears despite scrolling down.

Here my code and a working example at the bottom.

```<code>var mouseLastYPos = null;
$(document).mousemove(function(e){
    if(mouseLastYPos){
        if (e.pageY < mouseLastYPos && e.pageY <= 2){

           $('#mystuff').show();

        }
    }
    mouseLastYPos = e.pageY;
});
</code>```

Working example: http://jsfiddle.net/bmHbt/

答:
You Can use it:

```<code>(function($){
    var topValue = 50;
    var mouseY = 0;
    jQuery( "body" ).on('mousemove',function( event ) {
        mouseY = event.clientY;
        if(mouseY <= topValue) {

            alert('ok ');
        }

    });

})(jQuery);
</code>```

Another One here it is best for you :

```<code>$(document).bind("mouseleave", function(e) {
        if (e.pageY - $(window).scrollTop() <= 1) {
            // $('#BeforeYouLeaveDiv').show();
            alert('ok ');
            $(document).unbind("mouseleave");
        }
    });
</code>```

Body:
I have created a jQuery event that pops up a dialog when a visitor is leaving a page. I am using the e.pageY to detect the mouse position. when the mouse is at Y: less than 2, the dialog pops up. the problem is, when the I scroll down through the page and decided to leave the page, the pop up does not show since the mouse is not at Y: less than 2. How can I fix that. i.e. when I leave the page and just hover over the address bar, a pop up appears despite scrolling down.

Here my code and a working example at the bottom.

var mouseLastYPos = null;
$(document).mousemove(function(e){
    if(mouseLastYPos){
        if (e.pageY < mouseLastYPos && e.pageY <= 2){

           $('#mystuff').show();

        }
    }
    mouseLastYPos = e.pageY;
});

Working example: http://jsfiddle.net/bmHbt/

Body:
You Can use it:

(function($){
    var topValue = 50;
    var mouseY = 0;
    jQuery( "body" ).on('mousemove',function( event ) {
        mouseY = event.clientY;
        if(mouseY <= topValue) {

            alert('ok ');
        }

    });

})(jQuery);

Another One here it is best for you :

$(document).bind("mouseleave", function(e) {
        if (e.pageY - $(window).scrollTop() <= 1) {
            // $('#BeforeYouLeaveDiv').show();
            alert('ok ');
            $(document).unbind("mouseleave");
        }
    });


问:
Stretch and fill image in Bootstrap carousel
I am using bootstrap carousal and having some problem with image height and width. Even though I define it in the img attribute it still displays as original resolution. Following is the code I am using:

```<code><div class="col-md-6 col-sm-6">
    <div id="myCarousel" class="carousel slide">
        <div class="carousel-inner">
            <div class="item active">
                <img src="http://placehold.it/650x450/aaa&text=Item 3" height="300" width="300" />
            </div>
            <div class="item">
                <img src="http://placehold.it/350x350/aaa&text=Item 3" height="300" width="300" />
            </div>
            <div class="item">
                <img src="http://placehold.it/350x350/aaa&text=Item 3" height="300" width="300" />
            </div>
        </div>
        <!-- Controls -->
        <a class="left carousel-control" href="#myCarousel" data-slide="prev">
            <span class="icon-prev"></span>
        </a>
        <a class="right carousel-control" href="#myCarousel" data-slide="next">
            <span class="icon-next"></span>
        </a>
    </div>
</div>
</code>```

Here is demo of that.

What should I do to fill the image in a certain height and width regardless of its original resolution?

答:
img tag using "object-fit: cover" property

.carousel {
    height: 300px;
}

.carousel-inner {
    height: 100%;
}

.item {
    width: 100%;
    height: 100%;
}

.item img {
    object-fit: cover;
/*
    object-fit: fill;
    object-fit: none;
    object-fit: contain;
    object-fit: scale-down;
*/
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.0/css/bootstrap.min.css" />

<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.0/js/bootstrap.min.js"></script>

<div class="col-md-6 col-sm-6">

    <div id="myCarousel" class="carousel slide" data-ride="carousel">

        <!-- Indicators -->
        <ol class="carousel-indicators">
            <li data-target="#myCarousel" data-slide-to="0" class="active"></li>
            <li data-target="#myCarousel" data-slide-to="1"></li>
            <li data-target="#myCarousel" data-slide-to="2"></li>
        </ol>

        <!-- Wrapper for slides -->
        <div class="carousel-inner">

            <div class="item active" >
              <img src="http://placehold.it/650x450/aaa&text=Item 1" style="width: 100%; height: 100%" />
            </div>

            <div class="item" >
              <img src="http://placehold.it/350x350/aaa&text=Item 2" style="width: 100%; height: 100%" />
            </div>

            <div class="item" >
              <img src="http://placehold.it/350x350/aaa&text=Item 3" style="width: 100%; height: 100%" />
            </div>

        </div>

        <!-- Left and right controls -->

            <span class="glyphicon glyphicon-chevron-left"></span>
            <span class="sr-only">Previous</span>

            <span class="glyphicon glyphicon-chevron-right"></span>
            <span class="sr-only">Next</span>

    </div>

</div></code>```

Codepen

Editor

Full view

Version of background .item

Body:
I am using bootstrap carousal and having some problem with image height and width. Even though I define it in the img attribute it still displays as original resolution. Following is the code I am using:

Here is demo of that.

What should I do to fill the image in a certain height and width regardless of its original resolution?

Body:
img tag using "object-fit: cover" property

.carousel {
    height: 300px;
}

.carousel-inner {
    height: 100%;
}

.item {
    width: 100%;
    height: 100%;
}

.item img {
    object-fit: cover;
/*
    object-fit: fill;
    object-fit: none;
    object-fit: contain;
    object-fit: scale-down;
*/
}

<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.0/css/bootstrap.min.css" />

<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.0/js/bootstrap.min.js"></script>

<div class="col-md-6 col-sm-6">

    <div id="myCarousel" class="carousel slide" data-ride="carousel">

        <!-- Indicators -->
        <ol class="carousel-indicators">
            <li data-target="#myCarousel" data-slide-to="0" class="active"></li>
            <li data-target="#myCarousel" data-slide-to="1"></li>
            <li data-target="#myCarousel" data-slide-to="2"></li>
        </ol>

        <!-- Wrapper for slides -->
        <div class="carousel-inner">

            <div class="item active" >
              <img src="http://placehold.it/650x450/aaa&text=Item 1" style="width: 100%; height: 100%" />
            </div>

            <div class="item" >
              <img src="http://placehold.it/350x350/aaa&text=Item 2" style="width: 100%; height: 100%" />
            </div>

            <div class="item" >
              <img src="http://placehold.it/350x350/aaa&text=Item 3" style="width: 100%; height: 100%" />
            </div>

        </div>

        <!-- Left and right controls -->
        <a class="left carousel-control" href="#myCarousel" data-slide="prev">
            <span class="glyphicon glyphicon-chevron-left"></span>
            <span class="sr-only">Previous</span>
        </a>
        <a class="right carousel-control" href="#myCarousel" data-slide="next">
            <span class="glyphicon glyphicon-chevron-right"></span>
            <span class="sr-only">Next</span>
        </a>

    </div>

</div>

Codepen

Editor

Full view

Version of background .item


问:
how to check if a file exist and is a text file?
Hi everyone I need to check if a file exist with a shell script. I did some digging and ended up with this syntax but I'm not sure why it isn't working
(please bear in mind that you are talking to beginner)

I've found that you can add -e for example to check if it exist but I didn't get where these shortcuts came form or their names

#! /bin/bash
if [ "$#" = "1" ]
then
    if [ -e $($1) ] && [ -f $($1) ]
        then echo 'the file exists'
    fi

fi
```

答:
In idiomatic Bash:

```<code>#!/usr/bin/env bash

if [[ -f "${1-}" ]]
then
    echo 'the file exists'
fi
</code>```

Correct shebang

[[ rather than [

-f implies -e

No need for semicolons or single-use variables.

Please keep in mind that this does not tell you whether the file is a text file. The only "definition" of a text file as opposed to any other file is whether it contains only printable characters, and even that falls short of dealing with UTF BOM characters and non-ASCII character sets. For that you may want to look at the non-authoritative output of file "${1-}", for example:

```<code>$ file ~/.bashrc
/home/username/.bashrc: ASCII text
</code>```

More in the Bash Guide.

Body:
In idiomatic Bash:

#!/usr/bin/env bash

if [[ -f "${1-}" ]]
then
    echo 'the file exists'
fi

Correct shebang

[[ rather than [

-f implies -e

No need for semicolons or single-use variables.

Please keep in mind that this does not tell you whether the file is a text file. The only "definition" of a text file as opposed to any other file is whether it contains only printable characters, and even that falls short of dealing with UTF BOM characters and non-ASCII character sets. For that you may want to look at the non-authoritative output of file "${1-}", for example:

$ file ~/.bashrc
/home/username/.bashrc: ASCII text

More in the Bash Guide.


问:
Finding whether a date falls within the date range using XSLT
I have the following xml:

```<code><?xml version="1.0" encoding="UTF-8"?>
<divisions>
   <userProvidedEffDate>12/31/2002</userProvidedEffDate>
   <division>
      <GroupNumber>001</GroupNumber>
      <GroupEffDt>01/01/2000</GroupEffDt>
      <GroupExpDt>12/31/9999</GroupExpDt>
   </division>
   <division>
      <GroupNumber>002</GroupNumber>
      <GroupEffDt>01/01/2000</GroupEffDt>
      <GroupExpDt>12/31/2001</GroupExpDt>
   </division>
</divisions>
</code>```

Now I want to tranasform the above xml using XSLT 1.0 based on the value of <userProvidedEffDate>. If the <userProvidedEffDate> is in between the date range of the <division>'s <GroupEffDt> and <GroupExpDt>(inclusive), then we display that division. For example the above input xml should be transformed as below based on the <userProvidedEffDate> value 12/31/2002.

```<code><?xml version="1.0" encoding="UTF-8"?>
<divisions>
   <userProvidedEffDate>12/31/2002</userProvidedEffDate>
   <division>
      <GroupNumber>001</GroupNumber>
      <GroupEffDt>01/01/2000</GroupEffDt>
      <GroupExpDt>12/31/9999</GroupExpDt>
   </division>
</divisions>
</code>```

Any help is appreciated.

答:
This is tedious, but not too difficult:

XSLT 1.0

```<code><xsl:stylesheet version="1.0"
xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:output method="xml" version="1.0" encoding="UTF-8" indent="yes"/>
<xsl:strip-space elements="*"/>

<xsl:template match="/divisions">
    <xsl:variable name="userDate">
        <xsl:value-of select="substring(userProvidedEffDate, 7, 4)"/>
        <xsl:value-of select="substring(userProvidedEffDate, 1, 2)"/>
        <xsl:value-of select="substring(userProvidedEffDate, 4, 2)"/>
    </xsl:variable>
    <xsl:copy>
        <xsl:for-each select="division">
            <xsl:variable name="effDate">
                <xsl:value-of select="substring(GroupEffDt, 7, 4)"/>
                <xsl:value-of select="substring(GroupEffDt, 1, 2)"/>
                <xsl:value-of select="substring(GroupEffDt, 4, 2)"/>
            </xsl:variable>
            <xsl:variable name="expDate">
                <xsl:value-of select="substring(GroupExpDt, 7, 4)"/>
                <xsl:value-of select="substring(GroupExpDt, 1, 2)"/>
                <xsl:value-of select="substring(GroupExpDt, 4, 2)"/>
            </xsl:variable>
            <xsl:if test="$effDate <= $userDate and $userDate <= $expDate">
                <xsl:copy-of select="."/>
            </xsl:if>
        </xsl:for-each>
    </xsl:copy>
</xsl:template>

</xsl:stylesheet>
</code>```

Body:
I have the following xml:

<?xml version="1.0" encoding="UTF-8"?>
<divisions>
   <userProvidedEffDate>12/31/2002</userProvidedEffDate>
   <division>
      <GroupNumber>001</GroupNumber>
      <GroupEffDt>01/01/2000</GroupEffDt>
      <GroupExpDt>12/31/9999</GroupExpDt>
   </division>
   <division>
      <GroupNumber>002</GroupNumber>
      <GroupEffDt>01/01/2000</GroupEffDt>
      <GroupExpDt>12/31/2001</GroupExpDt>
   </division>
</divisions>

Now I want to tranasform the above xml using XSLT 1.0 based on the value of <userProvidedEffDate>. If the <userProvidedEffDate> is in between the date range of the <division>'s <GroupEffDt> and <GroupExpDt>(inclusive), then we display that division. For example the above input xml should be transformed as below based on the <userProvidedEffDate> value 12/31/2002.

<?xml version="1.0" encoding="UTF-8"?>
<divisions>
   <userProvidedEffDate>12/31/2002</userProvidedEffDate>
   <division>
      <GroupNumber>001</GroupNumber>
      <GroupEffDt>01/01/2000</GroupEffDt>
      <GroupExpDt>12/31/9999</GroupExpDt>
   </division>
</divisions>

Any help is appreciated.

Body:
This is tedious, but not too difficult:

XSLT 1.0

<xsl:stylesheet version="1.0"
xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:output method="xml" version="1.0" encoding="UTF-8" indent="yes"/>
<xsl:strip-space elements="*"/>

<xsl:template match="/divisions">
    <xsl:variable name="userDate">
        <xsl:value-of select="substring(userProvidedEffDate, 7, 4)"/>
        <xsl:value-of select="substring(userProvidedEffDate, 1, 2)"/>
        <xsl:value-of select="substring(userProvidedEffDate, 4, 2)"/>
    </xsl:variable>
    <xsl:copy>
        <xsl:for-each select="division">
            <xsl:variable name="effDate">
                <xsl:value-of select="substring(GroupEffDt, 7, 4)"/>
                <xsl:value-of select="substring(GroupEffDt, 1, 2)"/>
                <xsl:value-of select="substring(GroupEffDt, 4, 2)"/>
            </xsl:variable>
            <xsl:variable name="expDate">
                <xsl:value-of select="substring(GroupExpDt, 7, 4)"/>
                <xsl:value-of select="substring(GroupExpDt, 1, 2)"/>
                <xsl:value-of select="substring(GroupExpDt, 4, 2)"/>
            </xsl:variable>
            <xsl:if test="$effDate &lt;= $userDate and $userDate &lt;= $expDate">
                <xsl:copy-of select="."/>
            </xsl:if>
        </xsl:for-each>
    </xsl:copy>
</xsl:template>

</xsl:stylesheet>


问:
If statement within look error 13 - type error
I have boolean or #N/A values in column DO. If a True boolean is within the DO column range, I wish for the corresponding cell in range r3FTop to be changed to the colour as per my code. My thinking is that DO2 cell corresponds to X5, and the D03 to X2.

When i run this code with

```<code>Set rRng = Worksheets("mapOut").Range("DO2:DO2") and
Set r3FTop = Worksheets("mapOut").Range("X5")
</code>```

the code works fine (cells turn to orange when the cell value at DO2 is True and don't when the cell value is False or #N/A). However upon adding the next cell in each range (DO3 and X2) I keep getting the type 13 error.

I've tried the bottom on the first row and it colours the cell at X5 perfectly. I run into problems when I try and add a second cell to the range.

For ease of use I have opted to batch the cell references I wish to colour in a group as they appear on screen.

```<code>Sub toCheckOut()

Dim rCell As Range
Dim rRng As Range
Dim r3FTop As Range

' check out check column
Set rRng = Worksheets("mapOut").Range("DO2:DO3")

Set r3FTop = Worksheets("mapOut").Range("X5", "X2")

For Each rCell In rRng.Cells
    If rRng.Value = False Then
        GoTo Continue

    ElseIf rRng.Value = True Then
        r3FTop.Interior.Color = RGB(237, 125, 49)

    Else
        GoTo Continue

    End If

Continue:

    Next rCell

End Sub
</code>```

My actual column range is DO2:DO90 and I have corresponding cell values for r3FTop variable too. I wish for the code to go though and disregard and #N/A or False values and only change corresponding cell colors when a True boolean is found.

I've tried rewriting the above code so that the True boolean is dealt with first as so with dealing with blanks (using application.worksheet.isna(rRng).

Any pointers would be greatly appreciated.

答:
This should Work now:</p>

```<code>Sub toCheckOut()

Dim rCell As Range
Dim rRng As Range
Dim r3FTop As Range
Dim arr(1) as String
Dim i as Integer

i = 0

 ' check out check column
Set rRng = Worksheets("mapOut").Range("DO2:DO3")

arr(0) = "5"
arr(1) = "2"
'Set r3FTop = Worksheets("mapOut").Range("X5", "X2")

For Each rCell In rRng.Cells
    If rRng.Value = False Then
        GoTo Continue

    ElseIf rRng.Value = True Then
         Worksheets("mapOut").Range("X" & arr(i)).Interior.Color = RGB(237, 125, 49)
         i = i + 1
    Else
        GoTo Continue

    End If

Continue:

    Next rCell

End Sub
</code>```

Body:
I have boolean or #N/A values in column DO. If a True boolean is within the DO column range, I wish for the corresponding cell in range r3FTop to be changed to the colour as per my code. My thinking is that DO2 cell corresponds to X5, and the D03 to X2.

When i run this code with

Set rRng = Worksheets("mapOut").Range("DO2:DO2") and
Set r3FTop = Worksheets("mapOut").Range("X5")

the code works fine (cells turn to orange when the cell value at DO2 is True and don't when the cell value is False or #N/A). However upon adding the next cell in each range (DO3 and X2) I keep getting the type 13 error.

I've tried the bottom on the first row and it colours the cell at X5 perfectly. I run into problems when I try and add a second cell to the range.

For ease of use I have opted to batch the cell references I wish to colour in a group as they appear on screen.

Sub toCheckOut()

Dim rCell As Range
Dim rRng As Range
Dim r3FTop As Range

' check out check column
Set rRng = Worksheets("mapOut").Range("DO2:DO3")

Set r3FTop = Worksheets("mapOut").Range("X5", "X2")

For Each rCell In rRng.Cells
    If rRng.Value = False Then
        GoTo Continue

    ElseIf rRng.Value = True Then
        r3FTop.Interior.Color = RGB(237, 125, 49)

    Else
        GoTo Continue

    End If

Continue:

    Next rCell

End Sub

My actual column range is DO2:DO90 and I have corresponding cell values for r3FTop variable too. I wish for the code to go though and disregard and #N/A or False values and only change corresponding cell colors when a True boolean is found.

I've tried rewriting the above code so that the True boolean is dealt with first as so with dealing with blanks (using application.worksheet.isna(rRng).

Any pointers would be greatly appreciated.

Body:
This should Work now:

Sub toCheckOut()

Dim rCell As Range
Dim rRng As Range
Dim r3FTop As Range
Dim arr(1) as String
Dim i as Integer

i = 0

 ' check out check column
Set rRng = Worksheets("mapOut").Range("DO2:DO3")

arr(0) = "5"
arr(1) = "2"
'Set r3FTop = Worksheets("mapOut").Range("X5", "X2")

For Each rCell In rRng.Cells
    If rRng.Value = False Then
        GoTo Continue

    ElseIf rRng.Value = True Then
         Worksheets("mapOut").Range("X" & arr(i)).Interior.Color = RGB(237, 125, 49)
         i = i + 1
    Else
        GoTo Continue

    End If

Continue:

    Next rCell

End Sub


问:
What am I doing wrong? It shows me that the list index is out of range
I have a given list and I want to add all elements of that list with an odd index to the new list. Here is my code :

```<code>def odd_indices(lst):
  new_lst = [ lst[i] for i in lst if (i + 2) % 2 != 0 ]
  return new_lst
</code>```

What am I doing wrong?

答:
in the list comprehension[lst[i] for i in lst if (i + 2) % 2 != 0] you iterate over items in the list and try to obtain elements from the original list with the respective index i if i+2 is odd.

as mentioned in other replies you can use enumerate to access index and element.

or you can simply use slicing

```<code>>>> foo = [1, 2, 3, 4, 5]
>>> foo[1::2]
[2, 4]
</code>```

Body:
I have a given list and I want to add all elements of that list with an odd index to the new list. Here is my code :

def odd_indices(lst):
  new_lst = [ lst[i] for i in lst if (i + 2) % 2 != 0 ]
  return new_lst

What am I doing wrong?

Body:
in the list comprehension[lst[i] for i in lst if (i + 2) % 2 != 0] you iterate over items in the list and try to obtain elements from the original list with the respective index i if i+2 is odd.

as mentioned in other replies you can use enumerate to access index and element.

or you can simply use slicing

>>> foo = [1, 2, 3, 4, 5]
>>> foo[1::2]
[2, 4]


问:
How to pass a TComparer<T> class to a generic type in Delphi?
I want to create a generic record with some functionality, including a search function.
To perform this search I wanted to pass a custom Comparer to compare items.
If it were a class, I could pass it in the constructor, but I want to use a record to avoid to create or free it. So, I don't have a constructor where to initialize the Comparer.

Then I decided to pass the Comparer class like a Type parameter, and when I need the comparer, create a instance of the comparer using TComparer.Default.

Well, here is the code:

```<code>TMyArray<T,C: TComparer<T>> = record
  FComparer: IComparer<T>;
  Items: TArray<T>;

  function Contains<AItem: T>: Boolean;
end;
</code>```

The problem appears when I try to use it in this way:

```<code>TMyRecord = record
  Score: Real;
  A: string;
  B: string;
end;

TMyRecordComparer = class(TComparer<TMyRecord>)
  function Compare(Left, Right: TMyRecord): Integer;
end;

TMyRecordArray = TMyArray<TMyRecord, TMyRecordComparer>;
</code>```

With this last declaration, I get this error:
E2515 Type parameter 'T' is not compatible with type 'System.Generics.Defaults.TComparer\'.

Any idea how to solve this issue?

答:
The problem is the syntax of your constraint:

```<code>TMyArray<T,C: TComparer<T>>
</code>```

This constrains both T and C to be TComparer<T>.

Instead you need this:

```<code>TMyArray<T; C: TComparer<T>>
</code>```

The documentation gives examples of the various syntax options.

Body:
I want to create a generic record with some functionality, including a search function.
To perform this search I wanted to pass a custom Comparer to compare items.
If it were a class, I could pass it in the constructor, but I want to use a record to avoid to create or free it. So, I don't have a constructor where to initialize the Comparer.

Then I decided to pass the Comparer class like a Type parameter, and when I need the comparer, create a instance of the comparer using TComparer.Default.

Well, here is the code:

TMyArray<T,C: TComparer<T>> = record
  FComparer: IComparer<T>;
  Items: TArray<T>;

  function Contains<AItem: T>: Boolean;
end;

The problem appears when I try to use it in this way:

TMyRecord = record
  Score: Real;
  A: string;
  B: string;
end;

TMyRecordComparer = class(TComparer<TMyRecord>)
  function Compare(Left, Right: TMyRecord): Integer;
end;

TMyRecordArray = TMyArray<TMyRecord, TMyRecordComparer>;

With this last declaration, I get this error:
E2515 Type parameter 'T' is not compatible with type 'System.Generics.Defaults.TComparer\'.

Any idea how to solve this issue?

Body:
The problem is the syntax of your constraint:

TMyArray<T,C: TComparer<T>>

This constrains both T and C to be TComparer<T>.

Instead you need this:

TMyArray<T; C: TComparer<T>>

The documentation gives examples of the various syntax options.


问:
Left swipe for delete and edit,delete
I am not able to find a way around this. Is it possible to have delete option using left swipe and also using edit and delete.

I have edit button on the left of the navigation bar.

```<code>self.navigationItem.leftBarButtonItem = self.editButtonItem;
</code>```

and commitEditingStyle method as below

```<code>- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath {

    if (editingStyle == UITableViewCellEditingStyleDelete) {
//delete code here
    }
    else if (editingStyle == UITableViewCellEditingStyleInsert) {
    // Create a new instance of the appropriate class, insert it into the array, and add a new row to the table view.
    }
</code>```

}

After using this, the left swipe is not being detected at all. the only way to delete seems to be by going to the edit mode and deleting from there.
help would be appreciated.

I am a newbie so please go easy with me :)

答:
you mean swiping on cell you need delete option.

If so you can try this code:

```<code>- (UITableViewCellEditingStyle)tableView:(UITableView *)aTableView editingStyleForRowAtIndexPath:(NSIndexPath *)indexPath {

    return UITableViewCellEditingStyleDelete;

}

- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath {

    //perform delete operation

}
</code>```

ContentLicense: CC BY-SA 3.0

Title: Left swipe for delete and edit,delete

Body:
I am not able to find a way around this. Is it possible to have delete option using left swipe and also using edit and delete.

I have edit button on the left of the navigation bar.

self.navigationItem.leftBarButtonItem = self.editButtonItem;

and commitEditingStyle method as below

- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath {

    if (editingStyle == UITableViewCellEditingStyleDelete) {
//delete code here
    }
    else if (editingStyle == UITableViewCellEditingStyleInsert) {
    // Create a new instance of the appropriate class, insert it into the array, and add a new row to the table view.
    }

}

After using this, the left swipe is not being detected at all. the only way to delete seems to be by going to the edit mode and deleting from there.
help would be appreciated.

I am a newbie so please go easy with me :)

Body:
you mean swiping on cell you need delete option.

If so you can try this code:

- (UITableViewCellEditingStyle)tableView:(UITableView *)aTableView editingStyleForRowAtIndexPath:(NSIndexPath *)indexPath {

    return UITableViewCellEditingStyleDelete;

}

- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath {

    //perform delete operation

}


问:
How can I create and alter a new string[][] without altering the original?
I know this is an issue being caused by passing by reference rather than value, but I'm not sure what I need to do to fix it.

I have a field variable string[][] _cubeState which represents the state of a 2x2 Rubiks cube. This jagged array represents the state of the cube before any rotations take place and should be updated after every rotation, but only after my rotate method has returned and overwritten it.

What is actually happening is that when I get to the newCube[0][index] = _cubeState[0][index + 10]; line, this line updates both my newCube array and my original _cubeState array. Since the newCube is referencing cubeState it's also updating the original. How do I fix this so that the cubeState will only update after the method has returned?

```<code>private string[][] _cubeState;

public Rubiks () {
    _cubeState = new string[][] {
        new [] { "A", "A", "B", "B", "C", "C", "D", "D", "E", "E", "F", "F" },
        new [] { "A", "A", "B", "B", "C", "C", "D", "D", "E", "E", "F", "F" }
    };

    _cubeState = RotateAcw (0);
}

public string[][] RotateAcw (int index) {
    string[][] newCube = { _cubeState[0], _cubeState[1] };

    newCube[0][index] = _cubeState[0][index + 10];
    newCube[1][index] = _cubeState[1][index + 10];

    return newCube;
}
</code>```

答:
A bit shorter and slower alternative with Array.Clone :

```<code>string[][] newCube = Array.ConvertAll(_cubeState, x => x.Clone());
</code>```

Body:
I know this is an issue being caused by passing by reference rather than value, but I'm not sure what I need to do to fix it.

I have a field variable string[][] _cubeState which represents the state of a 2x2 Rubiks cube. This jagged array represents the state of the cube before any rotations take place and should be updated after every rotation, but only after my rotate method has returned and overwritten it.

What is actually happening is that when I get to the newCube[0][index] = _cubeState[0][index + 10]; line, this line updates both my newCube array and my original _cubeState array. Since the newCube is referencing cubeState it's also updating the original. How do I fix this so that the cubeState will only update after the method has returned?

private string[][] _cubeState;

public Rubiks () {
    _cubeState = new string[][] {
        new [] { "A", "A", "B", "B", "C", "C", "D", "D", "E", "E", "F", "F" },
        new [] { "A", "A", "B", "B", "C", "C", "D", "D", "E", "E", "F", "F" }
    };

    _cubeState = RotateAcw (0);
}

public string[][] RotateAcw (int index) {
    string[][] newCube = { _cubeState[0], _cubeState[1] };

    newCube[0][index] = _cubeState[0][index + 10];
    newCube[1][index] = _cubeState[1][index + 10];

    return newCube;
}

Body:
A bit shorter and slower alternative with Array.Clone :

string[][] newCube = Array.ConvertAll(_cubeState, x => x.Clone());


问:
How to create a Calendar table for 100 years in Sql
Suppose I want to store thousands of days in a table how will I retrieve it from the calendar?</p>

答:
Here is a generic script you can use in SQL server. just amend the start and end dates:

```<code>IF EXISTS (SELECT * FROM information_schema.tables WHERE Table_Name = 'Calendar' AND Table_Type = 'BASE TABLE')
BEGIN
DROP TABLE [Calendar]
END

CREATE TABLE [Calendar]
(
    [CalendarDate] DATETIME
)

DECLARE @StartDate DATETIME
DECLARE @EndDate DATETIME
SET @StartDate = GETDATE()
SET @EndDate = DATEADD(d, 365, @StartDate)

WHILE @StartDate <= @EndDate
      BEGIN
             INSERT INTO [Calendar]
             (
                   CalendarDate
             )
             SELECT
                   @StartDate

             SET @StartDate = DATEADD(dd, 1, @StartDate)
      END
</code>```

If you want a more advanced calendar here is one I found on the net a while ago:

```<code>CREATE SCHEMA Auxiliary
-- We put our auxiliary tables and stuff in a separate schema
-- One of the great new things in SQL Server 2005
go

CREATE FUNCTION Auxiliary.Computus
-- Computus (Latin for computation) is the calculation of the date of
-- Easter in the Christian calendar
-- http://en.wikipedia.org/wiki/Computus
-- I'm using the Meeus/Jones/Butcher Gregorian algorithm
(
    @Y INT -- The year we are calculating easter sunday for
)
RETURNS DATETIME
AS
BEGIN
DECLARE
@a INT,
@b INT,
@c INT,
@d INT,
@e INT,
@f INT,
@g INT,
@h INT,
@i INT,
@k INT,
@L INT,
@m INT

SET @a = @Y % 19
SET @b = @Y / 100
SET @c = @Y % 100
SET @d = @b / 4
SET @e = @b % 4
SET @f = (@b + 8) / 25
SET @g = (@b - @f + 1) / 3
SET @h = (19 * @a + @b - @d - @g + 15) % 30
SET @i = @c / 4
SET @k = @c % 4
SET @L = (32 + 2 * @e + 2 * @i - @h - @k) % 7
SET @m = (@a + 11 * @h + 22 * @L) / 451
RETURN(DATEADD(month, ((@h + @L - 7 * @m + 114) / 31)-1, cast(cast(@Y AS VARCHAR) AS Datetime)) + ((@h + @L - 7 * @m + 114) % 31))
END
GO

CREATE TABLE [Auxiliary].[Calendar] (
-- This is the calendar table
  [Date] datetime NOT NULL,
  [Year] int NOT NULL,
  [Quarter] int NOT NULL,
  [Month] int NOT NULL,
  [Week] int NOT NULL,
  [Day] int NOT NULL,
  [DayOfYear] int NOT NULL,
  [Weekday] int NOT NULL,
  [Fiscal_Year] int NOT NULL,
  [Fiscal_Quarter] int NOT NULL,
  [Fiscal_Month] int NOT NULL,
  [KindOfDay] varchar(10) NOT NULL,
  [Description] varchar(50) NULL,
  PRIMARY KEY CLUSTERED ([Date])
)
GO

ALTER TABLE [Auxiliary].[Calendar]
-- In Celkoish style I'm manic about constraints (Never use em ;-))
-- http://www.celko.com/

ADD CONSTRAINT [Calendar_ck] CHECK (  ([Year] > 1900)
AND ([Quarter] BETWEEN 1 AND 4)
AND ([Month] BETWEEN 1 AND 12)
AND ([Week]  BETWEEN 1 AND 53)
AND ([Day] BETWEEN 1 AND 31)
AND ([DayOfYear] BETWEEN 1 AND 366)
AND ([Weekday] BETWEEN 1 AND 7)
AND ([Fiscal_Year] > 1900)
AND ([Fiscal_Quarter] BETWEEN 1 AND 4)
AND ([Fiscal_Month] BETWEEN 1 AND 12)
AND ([KindOfDay] IN ('HOLIDAY', 'SATURDAY', 'SUNDAY', 'BANKDAY')))
GO

SET DATEFIRST 1;
-- I want my table to contain datedata acording to ISO 8601
-- http://en.wikipedia.org/wiki/ISO_8601
-- thus first day of a week is monday
WITH Dates(Date)
-- A recursive CTE that produce all dates between 1999 and 2020-12-31
AS
(
SELECT cast('1999' AS DateTime) Date -- SQL Server supports the ISO 8601 format so this is an unambigious shortcut for 1999-01-01
UNION ALL                            -- http://msdn2.microsoft.com/en-us/library/ms190977.aspx
SELECT (Date + 1) AS Date
FROM Dates
WHERE
Date < cast('2021' AS DateTime) -1
),

DatesAndThursdayInWeek(Date, Thursday)
-- The weeks can be found by counting the thursdays in a year so we find
-- the thursday in the week for a particular date
AS
(
SELECT
Date,
CASE DATEPART(weekday,Date)
WHEN 1 THEN Date + 3
WHEN 2 THEN Date + 2
WHEN 3 THEN Date + 1
WHEN 4 THEN Date
WHEN 5 THEN Date - 1
WHEN 6 THEN Date - 2
WHEN 7 THEN Date - 3
END AS Thursday
FROM Dates
),

Weeks(Week, Thursday)
-- Now we produce the weeknumers for the thursdays
-- ROW_NUMBER is new to SQL Server 2005
AS
(
SELECT ROW_NUMBER() OVER(partition by year(Date) order by Date) Week, Thursday
FROM DatesAndThursdayInWeek
WHERE DATEPART(weekday,Date) = 4
)
INSERT INTO Auxiliary.Calendar
SELECT
d.Date,
YEAR(d.Date) AS Year,
DATEPART(Quarter, d.Date) AS Quarter,
MONTH(d.Date) AS Month,
w.Week,
DAY(d.Date) AS Day,
DATEPART(DayOfYear, d.Date) AS DayOfYear,
DATEPART(Weekday, d.Date) AS Weekday,

-- Fiscal year may be different to the actual year in Norway the are the same
-- http://en.wikipedia.org/wiki/Fiscal_year
YEAR(d.Date) AS Fiscal_Year,
DATEPART(Quarter, d.Date) AS Fiscal_Quarter,
MONTH(d.Date) AS Fiscal_Month,

CASE
-- Holidays in Norway
-- For other countries and states: Wikipedia - List of holidays by country
-- http://en.wikipedia.org/wiki/List_of_holidays_by_country
    WHEN (DATEPART(DayOfYear, d.Date) = 1)          -- New Year's Day
    OR (d.Date = Auxiliary.Computus(YEAR(Date))-7)  -- Palm Sunday
    OR (d.Date = Auxiliary.Computus(YEAR(Date))-3)  -- Maundy Thursday
    OR (d.Date = Auxiliary.Computus(YEAR(Date))-2)  -- Good Friday
    OR (d.Date = Auxiliary.Computus(YEAR(Date)))    -- Easter Sunday
    OR (d.Date = Auxiliary.Computus(YEAR(Date))+39) -- Ascension Day
    OR (d.Date = Auxiliary.Computus(YEAR(Date))+49) -- Pentecost
    OR (d.Date = Auxiliary.Computus(YEAR(Date))+50) -- Whitmonday
    OR (MONTH(d.Date) = 5 AND DAY(d.Date) = 1)      -- Labour day
    OR (MONTH(d.Date) = 5 AND DAY(d.Date) = 17)     -- Constitution day
    OR (MONTH(d.Date) = 12 AND DAY(d.Date) = 25)    -- Cristmas day
    OR (MONTH(d.Date) = 12 AND DAY(d.Date) = 26)    -- Boxing day
    THEN 'HOLIDAY'
    WHEN DATEPART(Weekday, d.Date) = 6 THEN 'SATURDAY'
    WHEN DATEPART(Weekday, d.Date) = 7 THEN 'SUNDAY'
    ELSE 'BANKDAY'
END KindOfDay,
CASE
-- Description of holidays in Norway
    WHEN (DATEPART(DayOfYear, d.Date) = 1)            THEN 'New Year''s Day'
    WHEN (d.Date = Auxiliary.Computus(YEAR(Date))-7)  THEN 'Palm Sunday'
    WHEN (d.Date = Auxiliary.Computus(YEAR(Date))-3)  THEN 'Maundy Thursday'
    WHEN (d.Date = Auxiliary.Computus(YEAR(Date))-2)  THEN 'Good Friday'
    WHEN (d.Date = Auxiliary.Computus(YEAR(Date)))    THEN 'Easter Sunday'
    WHEN (d.Date = Auxiliary.Computus(YEAR(Date))+39) THEN 'Ascension Day'
    WHEN (d.Date = Auxiliary.Computus(YEAR(Date))+49) THEN 'Pentecost'
    WHEN (d.Date = Auxiliary.Computus(YEAR(Date))+50) THEN 'Whitmonday'
    WHEN (MONTH(d.Date) = 5 AND DAY(d.Date) = 1)      THEN 'Labour day'
    WHEN (MONTH(d.Date) = 5 AND DAY(d.Date) = 17)     THEN 'Constitution day'
    WHEN (MONTH(d.Date) = 12 AND DAY(d.Date) = 25)    THEN 'Cristmas day'
    WHEN (MONTH(d.Date) = 12 AND DAY(d.Date) = 26)    THEN 'Boxing day'
END Description

FROM DatesAndThursdayInWeek d
-- This join is for getting the week into the result set
     inner join Weeks w
     on d.Thursday = w.Thursday

OPTION(MAXRECURSION 0)
GO

CREATE FUNCTION Auxiliary.Numbers
(
@AFrom INT,
@ATo INT,
@AIncrement INT
)
RETURNS @RetNumbers TABLE
(
[Number] int PRIMARY KEY NOT NULL
)
AS
BEGIN
WITH Numbers(n)
AS
(
SELECT @AFrom AS n
UNION ALL
SELECT (n + @AIncrement) AS n
FROM Numbers
WHERE
n < @ATo
)
INSERT @RetNumbers
SELECT n from Numbers
OPTION(MAXRECURSION 0)
RETURN;
END
GO

CREATE FUNCTION Auxiliary.iNumbers
(
@AFrom INT,
@ATo INT,
@AIncrement INT
)
RETURNS TABLE
AS
RETURN(
WITH Numbers(n)
AS
(
SELECT @AFrom AS n
UNION ALL
SELECT (n + @AIncrement) AS n
FROM Numbers
WHERE
n < @ATo
)
SELECT n AS Number from Numbers
)
GO
</code>```

Body:
Here is a generic script you can use in SQL server. just amend the start and end dates:

IF EXISTS (SELECT * FROM information_schema.tables WHERE Table_Name = 'Calendar' AND Table_Type = 'BASE TABLE')
BEGIN
DROP TABLE [Calendar]
END

CREATE TABLE [Calendar]
(
    [CalendarDate] DATETIME
)

DECLARE @StartDate DATETIME
DECLARE @EndDate DATETIME
SET @StartDate = GETDATE()
SET @EndDate = DATEADD(d, 365, @StartDate)

WHILE @StartDate <= @EndDate
      BEGIN
             INSERT INTO [Calendar]
             (
                   CalendarDate
             )
             SELECT
                   @StartDate

             SET @StartDate = DATEADD(dd, 1, @StartDate)
      END

If you want a more advanced calendar here is one I found on the net a while ago:

CREATE SCHEMA Auxiliary
-- We put our auxiliary tables and stuff in a separate schema
-- One of the great new things in SQL Server 2005
go

CREATE FUNCTION Auxiliary.Computus
-- Computus (Latin for computation) is the calculation of the date of
-- Easter in the Christian calendar
-- http://en.wikipedia.org/wiki/Computus
-- I'm using the Meeus/Jones/Butcher Gregorian algorithm
(
    @Y INT -- The year we are calculating easter sunday for
)
RETURNS DATETIME
AS
BEGIN
DECLARE
@a INT,
@b INT,
@c INT,
@d INT,
@e INT,
@f INT,
@g INT,
@h INT,
@i INT,
@k INT,
@L INT,
@m INT

SET @a = @Y % 19
SET @b = @Y / 100
SET @c = @Y % 100
SET @d = @b / 4
SET @e = @b % 4
SET @f = (@b + 8) / 25
SET @g = (@b - @f + 1) / 3
SET @h = (19 * @a + @b - @d - @g + 15) % 30
SET @i = @c / 4
SET @k = @c % 4
SET @L = (32 + 2 * @e + 2 * @i - @h - @k) % 7
SET @m = (@a + 11 * @h + 22 * @L) / 451
RETURN(DATEADD(month, ((@h + @L - 7 * @m + 114) / 31)-1, cast(cast(@Y AS VARCHAR) AS Datetime)) + ((@h + @L - 7 * @m + 114) % 31))
END
GO

CREATE TABLE [Auxiliary].[Calendar] (
-- This is the calendar table
  [Date] datetime NOT NULL,
  [Year] int NOT NULL,
  [Quarter] int NOT NULL,
  [Month] int NOT NULL,
  [Week] int NOT NULL,
  [Day] int NOT NULL,
  [DayOfYear] int NOT NULL,
  [Weekday] int NOT NULL,
  [Fiscal_Year] int NOT NULL,
  [Fiscal_Quarter] int NOT NULL,
  [Fiscal_Month] int NOT NULL,
  [KindOfDay] varchar(10) NOT NULL,
  [Description] varchar(50) NULL,
  PRIMARY KEY CLUSTERED ([Date])
)
GO

ALTER TABLE [Auxiliary].[Calendar]
-- In Celkoish style I'm manic about constraints (Never use em ;-))
-- http://www.celko.com/

ADD CONSTRAINT [Calendar_ck] CHECK (  ([Year] > 1900)
AND ([Quarter] BETWEEN 1 AND 4)
AND ([Month] BETWEEN 1 AND 12)
AND ([Week]  BETWEEN 1 AND 53)
AND ([Day] BETWEEN 1 AND 31)
AND ([DayOfYear] BETWEEN 1 AND 366)
AND ([Weekday] BETWEEN 1 AND 7)
AND ([Fiscal_Year] > 1900)
AND ([Fiscal_Quarter] BETWEEN 1 AND 4)
AND ([Fiscal_Month] BETWEEN 1 AND 12)
AND ([KindOfDay] IN ('HOLIDAY', 'SATURDAY', 'SUNDAY', 'BANKDAY')))
GO

SET DATEFIRST 1;
-- I want my table to contain datedata acording to ISO 8601
-- http://en.wikipedia.org/wiki/ISO_8601
-- thus first day of a week is monday
WITH Dates(Date)
-- A recursive CTE that produce all dates between 1999 and 2020-12-31
AS
(
SELECT cast('1999' AS DateTime) Date -- SQL Server supports the ISO 8601 format so this is an unambigious shortcut for 1999-01-01
UNION ALL                            -- http://msdn2.microsoft.com/en-us/library/ms190977.aspx
SELECT (Date + 1) AS Date
FROM Dates
WHERE
Date < cast('2021' AS DateTime) -1
),

DatesAndThursdayInWeek(Date, Thursday)
-- The weeks can be found by counting the thursdays in a year so we find
-- the thursday in the week for a particular date
AS
(
SELECT
Date,
CASE DATEPART(weekday,Date)
WHEN 1 THEN Date + 3
WHEN 2 THEN Date + 2
WHEN 3 THEN Date + 1
WHEN 4 THEN Date
WHEN 5 THEN Date - 1
WHEN 6 THEN Date - 2
WHEN 7 THEN Date - 3
END AS Thursday
FROM Dates
),

Weeks(Week, Thursday)
-- Now we produce the weeknumers for the thursdays
-- ROW_NUMBER is new to SQL Server 2005
AS
(
SELECT ROW_NUMBER() OVER(partition by year(Date) order by Date) Week, Thursday
FROM DatesAndThursdayInWeek
WHERE DATEPART(weekday,Date) = 4
)
INSERT INTO Auxiliary.Calendar
SELECT
d.Date,
YEAR(d.Date) AS Year,
DATEPART(Quarter, d.Date) AS Quarter,
MONTH(d.Date) AS Month,
w.Week,
DAY(d.Date) AS Day,
DATEPART(DayOfYear, d.Date) AS DayOfYear,
DATEPART(Weekday, d.Date) AS Weekday,

-- Fiscal year may be different to the actual year in Norway the are the same
-- http://en.wikipedia.org/wiki/Fiscal_year
YEAR(d.Date) AS Fiscal_Year,
DATEPART(Quarter, d.Date) AS Fiscal_Quarter,
MONTH(d.Date) AS Fiscal_Month,

CASE
-- Holidays in Norway
-- For other countries and states: Wikipedia - List of holidays by country
-- http://en.wikipedia.org/wiki/List_of_holidays_by_country
    WHEN (DATEPART(DayOfYear, d.Date) = 1)          -- New Year's Day
    OR (d.Date = Auxiliary.Computus(YEAR(Date))-7)  -- Palm Sunday
    OR (d.Date = Auxiliary.Computus(YEAR(Date))-3)  -- Maundy Thursday
    OR (d.Date = Auxiliary.Computus(YEAR(Date))-2)  -- Good Friday
    OR (d.Date = Auxiliary.Computus(YEAR(Date)))    -- Easter Sunday
    OR (d.Date = Auxiliary.Computus(YEAR(Date))+39) -- Ascension Day
    OR (d.Date = Auxiliary.Computus(YEAR(Date))+49) -- Pentecost
    OR (d.Date = Auxiliary.Computus(YEAR(Date))+50) -- Whitmonday
    OR (MONTH(d.Date) = 5 AND DAY(d.Date) = 1)      -- Labour day
    OR (MONTH(d.Date) = 5 AND DAY(d.Date) = 17)     -- Constitution day
    OR (MONTH(d.Date) = 12 AND DAY(d.Date) = 25)    -- Cristmas day
    OR (MONTH(d.Date) = 12 AND DAY(d.Date) = 26)    -- Boxing day
    THEN 'HOLIDAY'
    WHEN DATEPART(Weekday, d.Date) = 6 THEN 'SATURDAY'
    WHEN DATEPART(Weekday, d.Date) = 7 THEN 'SUNDAY'
    ELSE 'BANKDAY'
END KindOfDay,
CASE
-- Description of holidays in Norway
    WHEN (DATEPART(DayOfYear, d.Date) = 1)            THEN 'New Year''s Day'
    WHEN (d.Date = Auxiliary.Computus(YEAR(Date))-7)  THEN 'Palm Sunday'
    WHEN (d.Date = Auxiliary.Computus(YEAR(Date))-3)  THEN 'Maundy Thursday'
    WHEN (d.Date = Auxiliary.Computus(YEAR(Date))-2)  THEN 'Good Friday'
    WHEN (d.Date = Auxiliary.Computus(YEAR(Date)))    THEN 'Easter Sunday'
    WHEN (d.Date = Auxiliary.Computus(YEAR(Date))+39) THEN 'Ascension Day'
    WHEN (d.Date = Auxiliary.Computus(YEAR(Date))+49) THEN 'Pentecost'
    WHEN (d.Date = Auxiliary.Computus(YEAR(Date))+50) THEN 'Whitmonday'
    WHEN (MONTH(d.Date) = 5 AND DAY(d.Date) = 1)      THEN 'Labour day'
    WHEN (MONTH(d.Date) = 5 AND DAY(d.Date) = 17)     THEN 'Constitution day'
    WHEN (MONTH(d.Date) = 12 AND DAY(d.Date) = 25)    THEN 'Cristmas day'
    WHEN (MONTH(d.Date) = 12 AND DAY(d.Date) = 26)    THEN 'Boxing day'
END Description

FROM DatesAndThursdayInWeek d
-- This join is for getting the week into the result set
     inner join Weeks w
     on d.Thursday = w.Thursday

OPTION(MAXRECURSION 0)
GO

CREATE FUNCTION Auxiliary.Numbers
(
@AFrom INT,
@ATo INT,
@AIncrement INT
)
RETURNS @RetNumbers TABLE
(
[Number] int PRIMARY KEY NOT NULL
)
AS
BEGIN
WITH Numbers(n)
AS
(
SELECT @AFrom AS n
UNION ALL
SELECT (n + @AIncrement) AS n
FROM Numbers
WHERE
n < @ATo
)
INSERT @RetNumbers
SELECT n from Numbers
OPTION(MAXRECURSION 0)
RETURN;
END
GO

CREATE FUNCTION Auxiliary.iNumbers
(
@AFrom INT,
@ATo INT,
@AIncrement INT
)
RETURNS TABLE
AS
RETURN(
WITH Numbers(n)
AS
(
SELECT @AFrom AS n
UNION ALL
SELECT (n + @AIncrement) AS n
FROM Numbers
WHERE
n < @ATo
)
SELECT n AS Number from Numbers
)
GO


问:
How to convert from flex UI to apache roayle
I have Main.MXML file within that I have another view ReportTab.mxml(canvas is root tag for this page) under this one I have more another page RaviReport.mxml(canvas is root tag for this page) within this page I having formItem once I submit them I need to get the data from Backed using RemoteObject tag and I have to render data in DATAGRID. When I am loading my Main.mxml file I can able to compile successfully but I am getting error in console.
EventDispatcher.js:74 Uncaught TypeError: indicatorClass is not a constructor
    at mx.containers.FormItem.mx_containers_FormItem_displayIndicator (FormItem.js:718)
    at mx.containers.FormItem.updateDisplayList (FormItem.js:397)
    at mx.containers.FormItem.updateFormItemDisplayList (FormItem.js:409)
    at mx.containers.FormItem.FormItemLayout.updateDisplayList (FormItem.js:1101)
    at mx.containers.FormItem.FormItemLayout.mx.containers.beads.BoxLayout.layout (BoxLayout.js:115)
    at mx.containers.FormItem.FormItemLayout.org.apache.royale.core.LayoutBase.performLayout (LayoutBase.js:247)
    at mx.containers.FormItem.FormItemLayout.org.apache.royale.core.LayoutBase.handleLayoutNeeded (LayoutBase.js:152)
    at mx.containers.FormItem.goog.events.EventTarget.fireListeners (eventtarget.js:284)
    at Function.goog.events.EventTarget.dispatchEventInternal_ (eventtarget.js:381)
    at mx.containers.FormItem.goog.events.EventTarget.dispatchEvent (eventtarget.js:196

I have tried removing FormItem and I have just added  in RaviReport.mxml but My canvas is hiding the label element. Please suggest me how to integrate view within using navigationBar or ViewSTACK in Royale.

Main.MXML

```<code><?xml version="1.0" encoding="utf-8"?>
<mx:Application xmlns:mx="http://www.adobe.com/2006/mxml" xmlns:view="com.sp.cpem.view.*" backgroundColor="#FFFFFF" verticalGap="0" horizontalGap="0" paddingTop="0" paddingLeft="2" paddingRight="2" paddingBottom="2" pageTitle="EXAMPLE">

    <mx:Script>
        <![CDATA[

    ]]>

    </mx:Script>

        <mx:ViewStack id="myViewStack" borderStyle="none" width="100%" height="100%">

            <view:ReportTAB id ="repo" label="REPORTING" />

        </mx:ViewStack>
</mx:Application>

**ReportTAB.MXML:**

<?xml version="1.0" encoding="utf-8"?>
<mx:Canvas xmlns:mx="http://www.adobe.com/2006/mxml" xmlns:view="com.sp.cpem.view.reports.*" width="100%" height="100%">
        <mx:TabNavigator width="100%" height="100%">

            <view:RaviReport id = "raviReport" label="Ravi Report"/>
        </mx:TabNavigator>
</mx:Canvas>

**RaviReport.MXML:**

<?xml version="1.0" encoding="utf-8"?>
<mx:Canvas xmlns:mx="http://www.adobe.com/2006/mxml" xmlns:view="com.sp.cpem.view.*" width="100%" height="100%" creationComplete="loadPage();">
    <mx:RemoteObject id="pageService" destination="pageService" result="handlePageResult(event)"  fault="handleFault(event)" showBusyCursor="true" />
    <mx:RemoteObject id="loaderService" destination="reportService" result="handleLoadResult(event)"  fault="handleFault(event)" showBusyCursor="true" />

    <mx:Script>
        <![CDATA[
            import com.sp.cpem.vo.StarsStdValues;
        import mx.managers.CursorManager;
        import com.as3xls.xls.Sheet;
        import com.as3xls.xls.ExcelFile;
        import mx.rpc.events.ResultEvent;
        import mx.rpc.events.FaultEvent;
        import mx.collections.ArrayCollection;
        import flash.net.FileReference;
        import mx.controls.Alert;

        private var pageArray:ArrayCollection = new ArrayCollection();
        private var fileReference:FileReference;
        private var sheet:Sheet;

        [Bindable]
        private var reportDG:ArrayCollection = new ArrayCollection();
        [Bindable]
        private var assetDP:ArrayCollection = new ArrayCollection();
        [Bindable]
        private var locationDP:ArrayCollection = new ArrayCollection();
        [Bindable]
        private var fields:Array = new Array();
        [Bindable]
        public var abcpRecords:int = 0;

        public var d:Date = null;

        import flash.external.*;

        private function exportToExcel():void{
            if(fromDate.selectedDate == null || toDate.selectedDate == null || asset.selectedItem == null || location.selectedItem == null )
                    Alert.show("Please input '*' required fields.","Information", Alert.OK, null, null, null, Alert.OK);
            else{
                var s:String;
                var locStr:String;
                d = DateField.stringToDate(toDate.text, toDate.formatString);
                d.hours = 23;
                d.minutes = 59;
                d.seconds = 59;
                d.milliseconds = 999;
                locStr='';
                //var myArray:Array = new Array(10);
                var myArray:Array = location.selectedItems;
                var obj:StarsStdValues;
                for (var i:uint; i < myArray.length; i++) {
                    obj = myArray[i];
                    if(i==0)
                        locStr = obj.value;
                    else
                        locStr = locStr+","+obj.value;
                }
                if (ExternalInterface.available) {
                    var formatter : DateFormatter;
                    formatter = new DateFormatter();
                    formatter.formatString = "DD.MMMM.YYYY KK:NN:SS A";
                    var jsFunction:String = "toABCPExcel";
                    s = ExternalInterface.call(jsFunction,formatter.format(fromDate.selectedDate),formatter.format(d),locStr);
                } else {
                    s = "JS not available";
                }
            }
        }

        /* We are using JSP to create report not FLEX due to 255 char limit issue
        private function exportToExcel1():void
        {
            sheet = new Sheet();
            var dataProviderCollection:ArrayCollection = dataGrid.dataProvider as ArrayCollection;
            var rowCount:int =  dataProviderCollection.length;
            var columns:Array = dataGrid.columns;
            var colCount:int =columns.length;
            sheet.resize(rowCount+4,colCount);
            var i:int = 0;
            for each (var field:DataGridColumn in columns){
                fields.push(field.dataField.toString());
                sheet.setCell(0,i,field.headerText.toString());
                i++;
            }

            for(var r:int=0;r<rowCount;r++)
            {
                var record:Object = dataProviderCollection.getItemAt(r);
                /*insert record starting from row no 2 else
                    headers will be overwritten* /
                insertRecordInSheet(r+1,sheet,record);
            }
            var xls:ExcelFile = new ExcelFile();
            xls.sheets.addItem(sheet);

            var bytes:ByteArray = xls.saveToByteArray();
            var fr:FileReference = new FileReference();
            fr.save(bytes,"LOCExposureReport.xls");

        }
        private function insertRecordInSheet(row:int,sheet:Sheet, record:Object):void
        {
            var i:int = 0;
            for each(var field:String in fields){
                if(record[field] == null){
                    //Do nothing if its null
                }else{
                    sheet.setCell(row,i,record[field].toString());
               }
               i++;
            }
            //Alert.show(record["comments"].toString(),"Information", Alert.OK, null, null, null, Alert.OK);
        }*/

            public function loadPage():void {
                pageService.getDP("ABCPReport");
            }
            private function handlePageResult(ev:ResultEvent):void {
                 pageArray = ev.result as ArrayCollection;
                 assetDP =pageArray[0] as ArrayCollection;
                 locationDP =pageArray[1] as ArrayCollection;
                 asset.selectedIndex = 0;
                 location.selectedIndex = 0;

            }

                public function getReport():void {
                //Alert.show(toDate.value.toString(),"Information", Alert.OK, null, null, null, Alert.OK);
                d = DateField.stringToDate(toDate.text, toDate.formatString);
                d.hours = 23;
                d.minutes = 59;
                d.seconds = 59;
                d.milliseconds = 999;
                //toDate.selectedDate = d;
                //toDate.selectedDate = DateField.dateToString(d, toDate.formatString);

                if(fromDate.selectedDate == null || toDate.selectedDate == null || asset.selectedItem == null || location.selectedItem == null )
                    Alert.show("Please input '*' required fields.","Information", Alert.OK, null, null, null, Alert.OK);
                else
                    loaderService.getReport(asset.selectedItems,fromDate.selectedDate,d,location.selectedItems); //toDate.selectedDate
            }

            private function handleLoadResult(ev:ResultEvent):void {
                 reportDG = ev.result as ArrayCollection;
                 abcpRecords = reportDG.length;
                 this.label = "ABCP Exposure Report (" +abcpRecords +")";
            }

            private function handleFault(ev:FaultEvent):void {
                Alert.show("Error: " + ev.fault.faultCode + " - " + ev.fault.faultDetail + " - " + ev.fault.faultString,"Information", Alert.OK, null, null, null, Alert.OK);
            }

            private function dateFunc( item:Object, column:DataGridColumn):String
            {
                return formatDate.format(item[column.dataField]);
            }

            //NUMERIC SORTING obj1[fieldName] sortCompareFunction="sortNumeric"
            private function sortMaturityDate(obj1:Object, obj2:Object):int {
                var value1:Date = (obj1.strmaturityDate =='' || obj1.strmaturityDate == null) ? null : new Date(obj1.strmaturityDate);
                var value2:Date = (obj2.strmaturityDate == '' || obj2.strmaturityDate == null) ? null : new Date(obj2.strmaturityDate);
                if (value1 < value2) {
                    return -1;
                } else if (value1 > value2) {
                    return 1;
                } else {
                    return 0;
                }
            }
        ]]>

    </mx:Script>
    <mx:DateFormatter id="formatDate" formatString ="D-MMM-YYYY"/>
    <mx:VDividedBox width="100%" height="100%">
            <mx:HBox height="15%" width="100%">
                <mx:FormItem label="Location:" required="true">
                    <mx:List id="location" dataProvider="{locationDP}" labelField="value" allowMultipleSelection="true" rowCount="4"/>
                </mx:FormItem>
                <mx:FormItem label="Asset Type:" required="true">
                    <mx:List id="asset" dataProvider="{assetDP}" labelField="value" allowMultipleSelection="true" rowCount="4"/>
                </mx:FormItem>

                <mx:FormItem label="From Date:" required="true">
                    <mx:DateField id="fromDate" yearNavigationEnabled="true"/>
                </mx:FormItem>
                <mx:FormItem label="To Date:" required="true">
                    <mx:DateField id="toDate" yearNavigationEnabled="true"/>
                </mx:FormItem>
                <mx:Button label="Submit" click="getReport()" toolTip="Exposure Report." />
                <mx:Button label="Save To Excel" click="exportToExcel();"/>
        </mx:HBox>
        <mx:VBox height="85%" width="100%">
            <mx:DataGrid id="dataGrid" height="100%" width="100%" dataProvider="{reportDG}" horizontalScrollPolicy="on">
                <mx:columns>
                    <mx:DataGridColumn dataField="alertId" headerText="Alert ID" showDataTips="true" dataTipField="alertId"/>

                </mx:columns>
            </mx:DataGrid>
        </mx:VBox>
    </mx:VDividedBox>
</mx:Canvas>
</code>```

ERROR
EventDispatcher.js:74 Uncaught TypeError: indicatorClass is not a constructor
    at mx.containers.FormItem.mx_containers_FormItem_displayIndicator (FormItem.js:718)
    at mx.containers.FormItem.updateDisplayList (FormItem.js:397)
    at mx.containers.FormItem.updateFormItemDisplayList (FormItem.js:409)
    at mx.containers.FormItem.FormItemLayout.updateDisplayList (FormItem.js:1101)
    at mx.containers.FormItem.FormItemLayout.mx.containers.beads.BoxLayout.layout (BoxLayout.js:115)
    at mx.containers.FormItem.FormItemLayout.org.apache.royale.core.LayoutBase.performLayout (LayoutBase.js:247)
    at mx.containers.FormItem.FormItemLayout.org.apache.royale.core.LayoutBase.handleLayoutNeeded (LayoutBase.js:152)
    at mx.containers.FormItem.goog.events.EventTarget.fireListeners (eventtarget.js:284)
    at Function.goog.events.EventTarget.dispatchEventInternal_ (eventtarget.js:381)
    at mx.containers.FormItem.goog.events.EventTarget.dispatchEvent (eventtarget.js:196

答:
my advice if that you start from a simple working file and start adding things to it.

In Royale there's no only one UI set like in Flex (MX/Spark). You can choose between Basic, Jewel, Emulation (MX/Spark), MDL. So first thing is: What UI Set you want to choose?. Take into account that Emulation (MX/Spark) is still a work in progress and is not fully working. Maybe Jewel or Basic will be more easy to do, but you require to adapta your UI code to this new tags and APIs.

For example, in Jewel you can check Tour de Jewel and the source code to see how it's done

HTH

Body:
I have Main.MXML file within that I have another view ReportTab.mxml(canvas is root tag for this page) under this one I have more another page RaviReport.mxml(canvas is root tag for this page) within this page I having formItem once I submit them I need to get the data from Backed using RemoteObject tag and I have to render data in DATAGRID. When I am loading my Main.mxml file I can able to compile successfully but I am getting error in console.
EventDispatcher.js:74 Uncaught TypeError: indicatorClass is not a constructor
    at mx.containers.FormItem.mx_containers_FormItem_displayIndicator (FormItem.js:718)
    at mx.containers.FormItem.updateDisplayList (FormItem.js:397)
    at mx.containers.FormItem.updateFormItemDisplayList (FormItem.js:409)
    at mx.containers.FormItem.FormItemLayout.updateDisplayList (FormItem.js:1101)
    at mx.containers.FormItem.FormItemLayout.mx.containers.beads.BoxLayout.layout (BoxLayout.js:115)
    at mx.containers.FormItem.FormItemLayout.org.apache.royale.core.LayoutBase.performLayout (LayoutBase.js:247)
    at mx.containers.FormItem.FormItemLayout.org.apache.royale.core.LayoutBase.handleLayoutNeeded (LayoutBase.js:152)
    at mx.containers.FormItem.goog.events.EventTarget.fireListeners (eventtarget.js:284)
    at Function.goog.events.EventTarget.dispatchEventInternal_ (eventtarget.js:381)
    at mx.containers.FormItem.goog.events.EventTarget.dispatchEvent (eventtarget.js:196

I have tried removing FormItem and I have just added  in RaviReport.mxml but My canvas is hiding the label element. Please suggest me how to integrate view within using navigationBar or ViewSTACK in Royale.

Main.MXML

<?xml version="1.0" encoding="utf-8"?>
<mx:Application xmlns:mx="http://www.adobe.com/2006/mxml" xmlns:view="com.sp.cpem.view.*" backgroundColor="#FFFFFF" verticalGap="0" horizontalGap="0" paddingTop="0" paddingLeft="2" paddingRight="2" paddingBottom="2" pageTitle="EXAMPLE">

    <mx:Script>
        <![CDATA[

    ]]>

    </mx:Script>

        <mx:ViewStack id="myViewStack" borderStyle="none" width="100%" height="100%">

            <view:ReportTAB id ="repo" label="REPORTING" />

        </mx:ViewStack>
</mx:Application>

**ReportTAB.MXML:**

<?xml version="1.0" encoding="utf-8"?>
<mx:Canvas xmlns:mx="http://www.adobe.com/2006/mxml" xmlns:view="com.sp.cpem.view.reports.*" width="100%" height="100%">
        <mx:TabNavigator width="100%" height="100%">

            <view:RaviReport id = "raviReport" label="Ravi Report"/>
        </mx:TabNavigator>
</mx:Canvas>

**RaviReport.MXML:**

<?xml version="1.0" encoding="utf-8"?>
<mx:Canvas xmlns:mx="http://www.adobe.com/2006/mxml" xmlns:view="com.sp.cpem.view.*" width="100%" height="100%" creationComplete="loadPage();">
    <mx:RemoteObject id="pageService" destination="pageService" result="handlePageResult(event)"  fault="handleFault(event)" showBusyCursor="true" />
    <mx:RemoteObject id="loaderService" destination="reportService" result="handleLoadResult(event)"  fault="handleFault(event)" showBusyCursor="true" />

    <mx:Script>
        <![CDATA[
            import com.sp.cpem.vo.StarsStdValues;
        import mx.managers.CursorManager;
        import com.as3xls.xls.Sheet;
        import com.as3xls.xls.ExcelFile;
        import mx.rpc.events.ResultEvent;
        import mx.rpc.events.FaultEvent;
        import mx.collections.ArrayCollection;
        import flash.net.FileReference;
        import mx.controls.Alert;

        private var pageArray:ArrayCollection = new ArrayCollection();
        private var fileReference:FileReference;
        private var sheet:Sheet;

        [Bindable]
        private var reportDG:ArrayCollection = new ArrayCollection();
        [Bindable]
        private var assetDP:ArrayCollection = new ArrayCollection();
        [Bindable]
        private var locationDP:ArrayCollection = new ArrayCollection();
        [Bindable]
        private var fields:Array = new Array();
        [Bindable]
        public var abcpRecords:int = 0;

        public var d:Date = null;

        import flash.external.*;

        private function exportToExcel():void{
            if(fromDate.selectedDate == null || toDate.selectedDate == null || asset.selectedItem == null || location.selectedItem == null )
                    Alert.show("Please input '*' required fields.","Information", Alert.OK, null, null, null, Alert.OK);
            else{
                var s:String;
                var locStr:String;
                d = DateField.stringToDate(toDate.text, toDate.formatString);
                d.hours = 23;
                d.minutes = 59;
                d.seconds = 59;
                d.milliseconds = 999;
                locStr='';
                //var myArray:Array = new Array(10);
                var myArray:Array = location.selectedItems;
                var obj:StarsStdValues;
                for (var i:uint; i < myArray.length; i++) {
                    obj = myArray[i];
                    if(i==0)
                        locStr = obj.value;
                    else
                        locStr = locStr+","+obj.value;
                }
                if (ExternalInterface.available) {
                    var formatter : DateFormatter;
                    formatter = new DateFormatter();
                    formatter.formatString = "DD.MMMM.YYYY KK:NN:SS A";
                    var jsFunction:String = "toABCPExcel";
                    s = ExternalInterface.call(jsFunction,formatter.format(fromDate.selectedDate),formatter.format(d),locStr);
                } else {
                    s = "JS not available";
                }
            }
        }

        /* We are using JSP to create report not FLEX due to 255 char limit issue
        private function exportToExcel1():void
        {
            sheet = new Sheet();
            var dataProviderCollection:ArrayCollection = dataGrid.dataProvider as ArrayCollection;
            var rowCount:int =  dataProviderCollection.length;
            var columns:Array = dataGrid.columns;
            var colCount:int =columns.length;
            sheet.resize(rowCount+4,colCount);
            var i:int = 0;
            for each (var field:DataGridColumn in columns){
                fields.push(field.dataField.toString());
                sheet.setCell(0,i,field.headerText.toString());
                i++;
            }

            for(var r:int=0;r<rowCount;r++)
            {
                var record:Object = dataProviderCollection.getItemAt(r);
                /*insert record starting from row no 2 else
                    headers will be overwritten* /
                insertRecordInSheet(r+1,sheet,record);
            }
            var xls:ExcelFile = new ExcelFile();
            xls.sheets.addItem(sheet);

            var bytes:ByteArray = xls.saveToByteArray();
            var fr:FileReference = new FileReference();
            fr.save(bytes,"LOCExposureReport.xls");

        }
        private function insertRecordInSheet(row:int,sheet:Sheet, record:Object):void
        {
            var i:int = 0;
            for each(var field:String in fields){
                if(record[field] == null){
                    //Do nothing if its null
                }else{
                    sheet.setCell(row,i,record[field].toString());
               }
               i++;
            }
            //Alert.show(record["comments"].toString(),"Information", Alert.OK, null, null, null, Alert.OK);
        }*/

            public function loadPage():void {
                pageService.getDP("ABCPReport");
            }
            private function handlePageResult(ev:ResultEvent):void {
                 pageArray = ev.result as ArrayCollection;
                 assetDP =pageArray[0] as ArrayCollection;
                 locationDP =pageArray[1] as ArrayCollection;
                 asset.selectedIndex = 0;
                 location.selectedIndex = 0;

            }

                public function getReport():void {
                //Alert.show(toDate.value.toString(),"Information", Alert.OK, null, null, null, Alert.OK);
                d = DateField.stringToDate(toDate.text, toDate.formatString);
                d.hours = 23;
                d.minutes = 59;
                d.seconds = 59;
                d.milliseconds = 999;
                //toDate.selectedDate = d;
                //toDate.selectedDate = DateField.dateToString(d, toDate.formatString);

                if(fromDate.selectedDate == null || toDate.selectedDate == null || asset.selectedItem == null || location.selectedItem == null )
                    Alert.show("Please input '*' required fields.","Information", Alert.OK, null, null, null, Alert.OK);
                else
                    loaderService.getReport(asset.selectedItems,fromDate.selectedDate,d,location.selectedItems); //toDate.selectedDate
            }

            private function handleLoadResult(ev:ResultEvent):void {
                 reportDG = ev.result as ArrayCollection;
                 abcpRecords = reportDG.length;
                 this.label = "ABCP Exposure Report (" +abcpRecords +")";
            }

            private function handleFault(ev:FaultEvent):void {
                Alert.show("Error: " + ev.fault.faultCode + " - " + ev.fault.faultDetail + " - " + ev.fault.faultString,"Information", Alert.OK, null, null, null, Alert.OK);
            }

            private function dateFunc( item:Object, column:DataGridColumn):String
            {
                return formatDate.format(item[column.dataField]);
            }

            //NUMERIC SORTING obj1[fieldName] sortCompareFunction="sortNumeric"
            private function sortMaturityDate(obj1:Object, obj2:Object):int {
                var value1:Date = (obj1.strmaturityDate =='' || obj1.strmaturityDate == null) ? null : new Date(obj1.strmaturityDate);
                var value2:Date = (obj2.strmaturityDate == '' || obj2.strmaturityDate == null) ? null : new Date(obj2.strmaturityDate);
                if (value1 < value2) {
                    return -1;
                } else if (value1 > value2) {
                    return 1;
                } else {
                    return 0;
                }
            }
        ]]>

    </mx:Script>
    <mx:DateFormatter id="formatDate" formatString ="D-MMM-YYYY"/>
    <mx:VDividedBox width="100%" height="100%">
            <mx:HBox height="15%" width="100%">
                <mx:FormItem label="Location:" required="true">
                    <mx:List id="location" dataProvider="{locationDP}" labelField="value" allowMultipleSelection="true" rowCount="4"/>
                </mx:FormItem>
                <mx:FormItem label="Asset Type:" required="true">
                    <mx:List id="asset" dataProvider="{assetDP}" labelField="value" allowMultipleSelection="true" rowCount="4"/>
                </mx:FormItem>

                <mx:FormItem label="From Date:" required="true">
                    <mx:DateField id="fromDate" yearNavigationEnabled="true"/>
                </mx:FormItem>
                <mx:FormItem label="To Date:" required="true">
                    <mx:DateField id="toDate" yearNavigationEnabled="true"/>
                </mx:FormItem>
                <mx:Button label="Submit" click="getReport()" toolTip="Exposure Report." />
                <mx:Button label="Save To Excel" click="exportToExcel();"/>
        </mx:HBox>
        <mx:VBox height="85%" width="100%">
            <mx:DataGrid id="dataGrid" height="100%" width="100%" dataProvider="{reportDG}" horizontalScrollPolicy="on">
                <mx:columns>
                    <mx:DataGridColumn dataField="alertId" headerText="Alert ID" showDataTips="true" dataTipField="alertId"/>

                </mx:columns>
            </mx:DataGrid>
        </mx:VBox>
    </mx:VDividedBox>
</mx:Canvas>

ERROR
EventDispatcher.js:74 Uncaught TypeError: indicatorClass is not a constructor
    at mx.containers.FormItem.mx_containers_FormItem_displayIndicator (FormItem.js:718)
    at mx.containers.FormItem.updateDisplayList (FormItem.js:397)
    at mx.containers.FormItem.updateFormItemDisplayList (FormItem.js:409)
    at mx.containers.FormItem.FormItemLayout.updateDisplayList (FormItem.js:1101)
    at mx.containers.FormItem.FormItemLayout.mx.containers.beads.BoxLayout.layout (BoxLayout.js:115)
    at mx.containers.FormItem.FormItemLayout.org.apache.royale.core.LayoutBase.performLayout (LayoutBase.js:247)
    at mx.containers.FormItem.FormItemLayout.org.apache.royale.core.LayoutBase.handleLayoutNeeded (LayoutBase.js:152)
    at mx.containers.FormItem.goog.events.EventTarget.fireListeners (eventtarget.js:284)
    at Function.goog.events.EventTarget.dispatchEventInternal_ (eventtarget.js:381)
    at mx.containers.FormItem.goog.events.EventTarget.dispatchEvent (eventtarget.js:196


问:
How to call On Premise API from Microsoft Bot C#
I am unable to make On Premise API calls from MS Bot (v4) C# once deployed on Azure. The On Premise API call works fine when locally tested with emulator.

As recommended by Microsoft support team, I have already tried using Direct Line channel for web chat but does not help.

```<code>                AppContext.SetSwitch("System.Net.Http.UseSocketsHttpHandler", false);

                HttpWebRequest webRequest = HttpWebRequest.CreateHttp(updatedURL);
                webRequest.Method = currentStep.StepsServiceCall.Method;
                webRequest.ContentType = "application/json";
                webRequest.KeepAlive = true;

                if (!String.IsNullOrEmpty(currentStep.StepsServiceCall.Headers))
                {
                    string updatedJson = currentStep.InjectPropertyValuesJson(currentStep.StepsServiceCall.Headers, properties);

                    webRequest.ContentLength = updatedJson.Length;

                    using (var streamWriter = new StreamWriter(webRequest.GetRequestStream()))
                    {
                        streamWriter.Write(updatedJson);
                        streamWriter.Flush();
                        streamWriter.Close();
                    }
                }

                using (HttpWebResponse response = webRequest.GetResponse() as HttpWebResponse)
                {
                    using (StreamReader reader = new StreamReader(response.GetResponseStream()))
                    {
                        string content = reader.ReadToEnd();

                        return await currentStep.ProcessResponseText(context, cancellationToken, content);
                    }
</code>```

Getting below error from Azure App Service logs.

Microsoft.Bot.Builder.Integration.AspNet.Core.BotFrameworkHttpAdapter: Exception caught : An error occurred while sending the request. Error 12029 calling WINHTTP_CALLBACK_STATUS_REQUEST_ERROR, 'A connection with the server could not be established'.

答:
To me the error message looks reasonably straight forward, your Azure App Service cannot reach the URL that your on-premise API is hosted on. Assuming that the server the API is hosted on responds to ICMP packets (pings) I would try the following:

Ping the URL from your local development machine - this can be done through command prompt/terminal ping <url-here>.

In Azure access the KUDU interface - go to App Service > Development Tools > Advanced tools > Go

In the one of the dropdown menus (tools I believe) there should be a command prompt option.

Attempt to ping the URL in the KUDU console.

If the ping fails then you will need to setup a route or update the URL you are using to use the FQDN as per this answer.

If the FQDN doesn't work then Azure Hybrid Connections are also a potential solution to your problem - a video is available here.

Body:
I am unable to make On Premise API calls from MS Bot (v4) C# once deployed on Azure. The On Premise API call works fine when locally tested with emulator.

As recommended by Microsoft support team, I have already tried using Direct Line channel for web chat but does not help.

                AppContext.SetSwitch("System.Net.Http.UseSocketsHttpHandler", false);

                HttpWebRequest webRequest = HttpWebRequest.CreateHttp(updatedURL);
                webRequest.Method = currentStep.StepsServiceCall.Method;
                webRequest.ContentType = "application/json";
                webRequest.KeepAlive = true;

                if (!String.IsNullOrEmpty(currentStep.StepsServiceCall.Headers))
                {
                    string updatedJson = currentStep.InjectPropertyValuesJson(currentStep.StepsServiceCall.Headers, properties);

                    webRequest.ContentLength = updatedJson.Length;

                    using (var streamWriter = new StreamWriter(webRequest.GetRequestStream()))
                    {
                        streamWriter.Write(updatedJson);
                        streamWriter.Flush();
                        streamWriter.Close();
                    }
                }

                using (HttpWebResponse response = webRequest.GetResponse() as HttpWebResponse)
                {
                    using (StreamReader reader = new StreamReader(response.GetResponseStream()))
                    {
                        string content = reader.ReadToEnd();

                        return await currentStep.ProcessResponseText(context, cancellationToken, content);
                    }

Getting below error from Azure App Service logs.

Microsoft.Bot.Builder.Integration.AspNet.Core.BotFrameworkHttpAdapter: Exception caught : An error occurred while sending the request. Error 12029 calling WINHTTP_CALLBACK_STATUS_REQUEST_ERROR, 'A connection with the server could not be established'.


问:
Coq: unfold tricky notations
Suppose I want to convert ~X to X -> False using unfold tactic.

I have two options how to do it: either by unfold not or by unfold "~".
The second way is apparently more convenient since there is no need to remember what definition name stays behind the notation.

However I haven't managed to do it in more complex cases:

```<code>Definition assn_sub X a P : Assertion :=
  fun (st : state) =>
    P (X !-> aeval st a ; st).

Notation "P [ X |-> a ]" := (assn_sub X a P)
  (at level 10, X at next level).
</code>```

and I want to unfold it in expression

```<code>((fun st0 : state => st0 Y = st0 X + st0 Z) [Z |-> Y - X]) st
</code>```

without using assn_sub. Is it possible?

答:
With underscores, it seems to work.</p>

```<code>unfold "_ [ _ |-> _ ]".
</code>```

Title: Coq: unfold tricky notations

Body:
Suppose I want to convert ~X to X -> False using unfold tactic.

I have two options how to do it: either by unfold not or by unfold "~".
The second way is apparently more convenient since there is no need to remember what definition name stays behind the notation.

However I haven't managed to do it in more complex cases:

Definition assn_sub X a P : Assertion :=
  fun (st : state) =>
    P (X !-> aeval st a ; st).

Notation "P [ X |-> a ]" := (assn_sub X a P)
  (at level 10, X at next level).

and I want to unfold it in expression

((fun st0 : state => st0 Y = st0 X + st0 Z) [Z |-> Y - X]) st

without using assn_sub. Is it possible?

Body:
With underscores, it seems to work.

unfold "_ [ _ |-> _ ]".


问:
Appending the mysql select result by group condition
I'm making a report where i need to summarize the results by joining several tables to get results by grouping the cd.line_id condition.
following is my select query.

```<code>SELECT bp.broadband_name,cd.line_id FROM broadband_service_master bp,dedint_account_services_table_wireless_pbx dp,
dedint_account_services_table das,dedint_account_table da,csr_deposit_change_history cd
 WHERE  bp.broadband_service_id=dp.service_id
 AND dp.dedint_service_table_id=das.id
 AND das.account_id=da.id
 AND cd.line_id=da.account_id
 GROUP BY cd.line_id
</code>```

I'm getting this :

```<code>broadband_name        line_id
--------------------  ---------

Equipment Support        344065
OffNet Landline Call     344065
Excess ONNET Calls       344065
Equipment Support        344066
International Call       344066
OffNet Landline Call     344066
Unlmtd ONNET Call        344066
</code>```

I need results like this:

```<code>broadband_name                                             line_id
--------------------                                      ---------

Equipment Support,OffNet Landline Call,Excess ONNET Calls    344065

Equipment Support,International Call ,OffNet Landline Call,Unlmtd ONNET Call 344066
</code>```

答:
try this..GROUP_CONCAT

```<code>SELECT GROUP_CONCAT(bp.broadband_name),cd.line_id FROM broadband_service_master bp,dedint_account_services_table_wireless_pbx dp,
dedint_account_services_table das,dedint_account_table da,csr_deposit_change_history cd
 WHERE  bp.broadband_service_id=dp.service_id
 AND dp.dedint_service_table_id=das.id
 AND das.account_id=da.id
 AND cd.line_id=da.account_id
 GROUP BY cd.line_id
</code>```

Body:
I'm making a report where i need to summarize the results by joining several tables to get results by grouping the cd.line_id condition.
following is my select query.

SELECT bp.broadband_name,cd.line_id FROM broadband_service_master bp,dedint_account_services_table_wireless_pbx dp,
dedint_account_services_table das,dedint_account_table da,csr_deposit_change_history cd
 WHERE  bp.broadband_service_id=dp.service_id
 AND dp.dedint_service_table_id=das.id
 AND das.account_id=da.id
 AND cd.line_id=da.account_id
 GROUP BY cd.line_id

I'm getting this :

broadband_name        line_id
--------------------  ---------

Equipment Support        344065
OffNet Landline Call     344065
Excess ONNET Calls       344065
Equipment Support        344066
International Call       344066
OffNet Landline Call     344066
Unlmtd ONNET Call        344066

I need results like this:

broadband_name                                             line_id
--------------------                                      ---------

Equipment Support,OffNet Landline Call,Excess ONNET Calls    344065

Equipment Support,International Call ,OffNet Landline Call,Unlmtd ONNET Call 344066

Body:
try this..GROUP_CONCAT

SELECT GROUP_CONCAT(bp.broadband_name),cd.line_id FROM broadband_service_master bp,dedint_account_services_table_wireless_pbx dp,
dedint_account_services_table das,dedint_account_table da,csr_deposit_change_history cd
 WHERE  bp.broadband_service_id=dp.service_id
 AND dp.dedint_service_table_id=das.id
 AND das.account_id=da.id
 AND cd.line_id=da.account_id
 GROUP BY cd.line_id


问:
Understanding Rails singular and plural paths
I'm very new to using Rails and at the moment am building an Instagram clone as a project to help me understand Rails a bit better. I am following this very helpful tutorial on how to implement the likes/unlikes feature:

https://medium.com/full-taxx/how-to-add-likes-to-posts-in-rails-e81430101bc2

However, I don't fully understand the Rails paths - please could someone explain the difference between:

post_like_path and post_likes_path as mentioned in the tutorial. I cannot see why one is like and one is likes? :(

Really trying to get my head around this so would be so grateful for any insight!

Thanks :)

答:
post model can have multiple likes. But when we do undo like it will be singular right. so post_like_path will handle the single like and it's going to trigger "delete" action in controller.

post_likes_path will trigger the new action for for creating new like.

Please routes resources concept then you come to know more about it.