问:
SQL Server Update statement to change year and month of a datetime column
I want to update the TimeOccurred column in all tables in a database (also fine with doing 1 table at a time if that is necessary). This is what the current values in this column look like:

```<code>2017-06-12 14:34:00
</code>```

I would like to replace that value in all tables in the column TimeOccurred by changing just the year to the current year and the month to the previous month.

So 2012-03-14 14:34:00 becomes 2017-05-14 14:34:00.

It would also help if I could check the day and if it was 29,30,or 31 change it to 25.

Update:

It's -1 month based on the current right now month. We want to change the days in case the month ends up being February, we can't have an event happening on February 31st for example. So all events should be days 1-28 to be safe.

More sample data:

```<code>2014-07-28 13:03:00
2012-07-28 13:03:00
2015-07-28 13:03:00
2014-07-28 13:03:00
2015-07-28 13:03:00
2016-07-29 11:02:00
2013-07-29 11:07:00
2005-07-29 11:12:00
2010-07-29 14:37:00
2015-07-29 14:37:00
2015-07-29 14:37:00
2015-07-29 14:37:00
2015-07-29 14:37:00
2015-07-29 14:37:00
2015-07-29 14:37:00
2015-07-29 14:37:00
2015-07-29 14:37:00
2015-07-29 14:37:00
2015-07-29 14:37:00
2015-07-29 14:37:00
</code>```

答:
try something like this</p>

```<code>UPDATE Your_Table
SET TimeOccurred = DATEADD(MM, -1, TimeOccurred)
</code>```

Body:
I want to update the TimeOccurred column in all tables in a database (also fine with doing 1 table at a time if that is necessary). This is what the current values in this column look like:

2017-06-12 14:34:00

I would like to replace that value in all tables in the column TimeOccurred by changing just the year to the current year and the month to the previous month.

So 2012-03-14 14:34:00 becomes 2017-05-14 14:34:00.

It would also help if I could check the day and if it was 29,30,or 31 change it to 25.

Update:

It's -1 month based on the current right now month. We want to change the days in case the month ends up being February, we can't have an event happening on February 31st for example. So all events should be days 1-28 to be safe.

More sample data:

2014-07-28 13:03:00
2012-07-28 13:03:00
2015-07-28 13:03:00
2014-07-28 13:03:00
2015-07-28 13:03:00
2016-07-29 11:02:00
2013-07-29 11:07:00
2005-07-29 11:12:00
2010-07-29 14:37:00
2015-07-29 14:37:00
2015-07-29 14:37:00
2015-07-29 14:37:00
2015-07-29 14:37:00
2015-07-29 14:37:00
2015-07-29 14:37:00
2015-07-29 14:37:00
2015-07-29 14:37:00
2015-07-29 14:37:00
2015-07-29 14:37:00
2015-07-29 14:37:00

Body:
try something like this

UPDATE Your_Table
SET TimeOccurred = DATEADD(MM, -1, TimeOccurred)


来源: stackexchange

问:
Get SVG root element and its children from an <object> node to export SVG with dynamic content
I have made a billing model made in InkScape (because I love SVG).
I'd like to generate new SVG without having to do it manually in InkScape (update the date, the amount, the customer email etc).

To achieve that this is what I've came up so far (a lot of this code where found on other post about SVG and Javscript) :

To make it easy, let's say I have a HTML page with an  which is displaying my billing model

```<code><button onclick="addDownloadLink()">Add download hyperlink</button>
<br />
<div id="exportLinkContainer"></div>
<br />
<!-- Size is based on a ratio of 210x297 -->
<object id="svgObject" data="./BillingModel.svg" type="image/svg+xml" width="630" height="891">No SVG support</object>
</code>```

On a button action, i call a javascript function

```<code>function addDownloadLink() {
    var svgObject = document.getElementById("svgObject").contentDocument;

    // THIS IS HERE where I can't find how to get the root svg element and all its attributs.
    var svg = svgObject.getElementById("svg").innerHTML;
    var svg2 = svgObject.getElementsByTagName("svg")[0].innerHTML;
    console.log("svg: " + svg);
    console.log("svg2: " + svg2);

    var blob = new Blob([svg], { type: "image/svg+xml;charset=utf-8" });
    var dateNow = new Date().toLocaleDateString();
    var downloadLink = document.createElement("a");
    downloadLink.appendChild(document.createTextNode("Download " + dateNow));
    downloadLink.setAttribute("download", "BillingExport___" + dateNow + ".svg");
    downloadLink.setAttribute("target", "_blank");
    downloadLink.setAttribute("href-lang", 'image/svg+xml');
    downloadLink.setAttribute("href", URL.createObjectURL(blob));

    var exportLinkContainer = document.getElementById("exportLinkContainer");
    exportContainer.innerHTML = '';
    exportContainer.appendChild(downloadLink);
}
</code>```

And here is an exemple of my svg file named BillingExportModel.svg :

```<code><?xml version="1.0" encoding="UTF-8" standalone="no"?>
<svg
    xmlns:dc="http://purl.org/dc/elements/1.1/"
    xmlns:cc="http://creativecommons.org/ns#"
    xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#"
    xmlns:svg="http://www.w3.org/2000/svg"
    xmlns="http://www.w3.org/2000/svg"
    xmlns:sodipodi="http://sodipodi.sourceforge.net/DTD/sodipodi-0.dtd"
    xmlns:inkscape="http://www.inkscape.org/namespaces/inkscape"
    sodipodi:docname="BillingExportModel.svg"
    inkscape:export-filename="/Users/Racine/Desktop/facture_1703_microsoft.png"
    height="297mm"
    width="210mm"
    inkscape:export-xdpi="202"
    version="1.1"
    inkscape:export-ydpi="202"
    inkscape:version="0.91 r13725"
    viewBox="0 0 210 297"
    id="svg">
    <!-- My script manage to get everything here inside the SVG root element. I need to get its parent and all its attributs. -->
    <!-- presentation stuff etc hidden because of not being usefull -->
    <text
        style="word-spacing:0px;letter-spacing:0px"
        line-height="125%"
        xml:space="preserve"
        y="134.65009"
        x="175.17645"
        sodipodi:linespacing="125%"
        id="text206">
        <tspan
            id="TextArticleTotal"
            sodipodi:role="line"
            x="175.17645"
            y="134.65009">1 450,00 €</tspan>
    </text>
    <!-- etc etc etc -->
</svg>
</code>```

It almost works expet that I don't manage to get the svg root element and all attributs like viewbox etc. But I have all the SVG content which is nice.

I can still copy all the svg root node inside my script in a var and concatenate that with I manage to have but I'm not happy with this solution and think I can do better.

Any help would be very appreciate ;)
Thanks

答:
The answer was easy (thank you Robert Longson) :

```<code>var svgObject = document.getElementById("svgObject").contentDocument;
var svg = svgObject.getElementById("svg").outerHTML;
</code>```

Don't do that :
    var svgObject = document.getElementById("svgObject").outerHTML;

Do : Add an id to the root element (and take care, Inksscape tend to use svg2 or svg3).

ContentLicense: CC BY-SA 3.0

Body:
I have made a billing model made in InkScape (because I love SVG).
I'd like to generate new SVG without having to do it manually in InkScape (update the date, the amount, the customer email etc).

To achieve that this is what I've came up so far (a lot of this code where found on other post about SVG and Javscript) :

To make it easy, let's say I have a HTML page with an  which is displaying my billing model

<button onclick="addDownloadLink()">Add download hyperlink</button>

<object id="svgObject" data="./BillingModel.svg" type="image/svg+xml" width="630" height="891">No SVG support</object>

On a button action, i call a javascript function

function addDownloadLink() {
    var svgObject = document.getElementById("svgObject").contentDocument;

    // THIS IS HERE where I can't find how to get the root svg element and all its attributs.
    var svg = svgObject.getElementById("svg").innerHTML;
    var svg2 = svgObject.getElementsByTagName("svg")[0].innerHTML;
    console.log("svg: " + svg);
    console.log("svg2: " + svg2);

    var blob = new Blob([svg], { type: "image/svg+xml;charset=utf-8" });
    var dateNow = new Date().toLocaleDateString();
    var downloadLink = document.createElement("a");
    downloadLink.appendChild(document.createTextNode("Download " + dateNow));
    downloadLink.setAttribute("download", "BillingExport___" + dateNow + ".svg");
    downloadLink.setAttribute("target", "_blank");
    downloadLink.setAttribute("href-lang", 'image/svg+xml');
    downloadLink.setAttribute("href", URL.createObjectURL(blob));

    var exportLinkContainer = document.getElementById("exportLinkContainer");
    exportContainer.innerHTML = '';
    exportContainer.appendChild(downloadLink);
}

And here is an exemple of my svg file named BillingExportModel.svg :

<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<svg
    xmlns:dc="http://purl.org/dc/elements/1.1/"
    xmlns:cc="http://creativecommons.org/ns#"
    xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#"
    xmlns:svg="http://www.w3.org/2000/svg"
    xmlns="http://www.w3.org/2000/svg"
    xmlns:sodipodi="http://sodipodi.sourceforge.net/DTD/sodipodi-0.dtd"
    xmlns:inkscape="http://www.inkscape.org/namespaces/inkscape"
    sodipodi:docname="BillingExportModel.svg"
    inkscape:export-filename="/Users/Racine/Desktop/facture_1703_microsoft.png"
    height="297mm"
    width="210mm"
    inkscape:export-xdpi="202"
    version="1.1"
    inkscape:export-ydpi="202"
    inkscape:version="0.91 r13725"
    viewBox="0 0 210 297"
    id="svg">

    <text
        style="word-spacing:0px;letter-spacing:0px"
        line-height="125%"
        xml:space="preserve"
        y="134.65009"
        x="175.17645"
        sodipodi:linespacing="125%"
        id="text206">
        <tspan
            id="TextArticleTotal"
            sodipodi:role="line"
            x="175.17645"
            y="134.65009">1 450,00 €</tspan>
    </text>

</svg>

It almost works expet that I don't manage to get the svg root element and all attributs like viewbox etc. But I have all the SVG content which is nice.

I can still copy all the svg root node inside my script in a var and concatenate that with I manage to have but I'm not happy with this solution and think I can do better.

Any help would be very appreciate ;)
Thanks

Body:
The answer was easy (thank you Robert Longson) :

var svgObject = document.getElementById("svgObject").contentDocument;
var svg = svgObject.getElementById("svg").outerHTML;

Don't do that :
    var svgObject = document.getElementById("svgObject").outerHTML;

Do : Add an id to the root element (and take care, Inksscape tend to use svg2 or svg3).


问:
VBA load large data from text file to Excel
I have a problem loading data to Excel from a text file.
The text file has about 230,000 lines and each line has exactly 130 characters. My goal is to get, from each line, specific data for what I'm trying to load the file into Excel and then retrieve the data I need.

First, I used the following code, but it takes about 7 minutes.

```<code>Sub leerTXT()
Dim strArchivo As String 'ruta del archivo
Dim intResultado As Integer 'resultado del dialogo

'---------- RUTA DEL ARCHIVO ----------
'Abrir dialog y preparar
Application.FileDialog(msoFileDialogOpen).AllowMultiSelect = False
intResultado = Application.FileDialog(msoFileDialogOpen).Show

'sólo si hay resultado positivo abrir fichero y leer
If intResultado <> 0 Then
    strArchivo = Application.FileDialog(msoFileDialogOpen).SelectedItems(1)
    On Error GoTo lblError:

Dim strFila As String 'filas que se van a leer
Dim iFila As Long  'numero de fila en la que se esta en el fichero
Dim jFila As Long 'numero de fila en el excel
'posicionarse en la fila 1
iFila = 1
jFila = 1

    'abrir el archivo
    Open strArchivo For Input As #1
    'loop mientras no se ha llegado al final del archivo
    Do Until EOF(1)

        If iFila Mod 70 > 17 Then
            'leer la fila actual
            Line Input #1, strFila

            'leer la linea y copiar a celda
            Cells(jFila, 1) = strFila

            jFila = jFila + 1
        End If

        'incrementar iFila en uno y pasar a la siguiente fila
        iFila = iFila + 1

    'loopear mientras condicion
    Loop

End If

'cerrar el archivo
Close #1

lblError:
If Err.Number <> 0 Then
MsgBox (Err.Number)
MsgBox (Err.Description)
Err.Clear
'cerrar el archivo
Close #1
End If

End Sub
</code>```

But as I said, that takes too long, so I searched for other ways and I saw something like the following:

```<code>Dim FSO As Object, MyFile As Object
Dim FileName As String, Arr As Variant
Dim f As Long

FileName = textfilename
Set FSO = CreateObject("Scripting.FileSystemObject")
Set MyFile = FSO.OpenTextFile(FileName, 1)
Arr = Split(MyFile.ReadAll, vbNewLine) ' Arr is zero-based array

Dim BigGuy(0 To UBound(Arr, 1), 1 To 1) As Long

Dim I As Long
For I = 0 To UBound(Arr)
    BigGuy(I, 1) = I
Next
'For test
'Fill column A from this Array Arr
   'UBound(Arr) + 1 Application.Transpose(
Range("A1:A500") = BigGuy
</code>```

The clue is to use array and paste range at it seems to be faster, but as the file is too long to transpose, I need to transpose it manually, but UBound(Arr) doesn't work and I don't know how to import the data.

And by the way, is there any way of just retrieving specific characters from the file (in an exact position), as every line has exactly the same length?

答:
Something like:</p>

```<code>Dim BigGuy()
Dim numLines As Long
Arr = Split(MyFile.ReadAll, vbNewLine) ' Arr is zero-based array

numLines = UBound(Arr) + 1

ReDim BigGuy(1 To numLines, 1 To 1)

Dim I As Long
For I = 0 To numLines-1
    BigGuy(I+1, 1) = Arr(I)
Next

Range("A1").Resize(numLines, 1) = BigGuy
</code>```

Body:
I have a problem loading data to Excel from a text file.
The text file has about 230,000 lines and each line has exactly 130 characters. My goal is to get, from each line, specific data for what I'm trying to load the file into Excel and then retrieve the data I need.

First, I used the following code, but it takes about 7 minutes.

Sub leerTXT()
Dim strArchivo As String 'ruta del archivo
Dim intResultado As Integer 'resultado del dialogo

'---------- RUTA DEL ARCHIVO ----------
'Abrir dialog y preparar
Application.FileDialog(msoFileDialogOpen).AllowMultiSelect = False
intResultado = Application.FileDialog(msoFileDialogOpen).Show

'sólo si hay resultado positivo abrir fichero y leer
If intResultado <> 0 Then
    strArchivo = Application.FileDialog(msoFileDialogOpen).SelectedItems(1)
    On Error GoTo lblError:

Dim strFila As String 'filas que se van a leer
Dim iFila As Long  'numero de fila en la que se esta en el fichero
Dim jFila As Long 'numero de fila en el excel
'posicionarse en la fila 1
iFila = 1
jFila = 1

    'abrir el archivo
    Open strArchivo For Input As #1
    'loop mientras no se ha llegado al final del archivo
    Do Until EOF(1)

        If iFila Mod 70 > 17 Then
            'leer la fila actual
            Line Input #1, strFila

            'leer la linea y copiar a celda
            Cells(jFila, 1) = strFila

            jFila = jFila + 1
        End If

        'incrementar iFila en uno y pasar a la siguiente fila
        iFila = iFila + 1

    'loopear mientras condicion
    Loop

End If

'cerrar el archivo
Close #1

lblError:
If Err.Number <> 0 Then
MsgBox (Err.Number)
MsgBox (Err.Description)
Err.Clear
'cerrar el archivo
Close #1
End If

End Sub

But as I said, that takes too long, so I searched for other ways and I saw something like the following:

Dim FSO As Object, MyFile As Object
Dim FileName As String, Arr As Variant
Dim f As Long

FileName = textfilename
Set FSO = CreateObject("Scripting.FileSystemObject")
Set MyFile = FSO.OpenTextFile(FileName, 1)
Arr = Split(MyFile.ReadAll, vbNewLine) ' Arr is zero-based array

Dim BigGuy(0 To UBound(Arr, 1), 1 To 1) As Long

Dim I As Long
For I = 0 To UBound(Arr)
    BigGuy(I, 1) = I
Next
'For test
'Fill column A from this Array Arr
   'UBound(Arr) + 1 Application.Transpose(
Range("A1:A500") = BigGuy

The clue is to use array and paste range at it seems to be faster, but as the file is too long to transpose, I need to transpose it manually, but UBound(Arr) doesn't work and I don't know how to import the data.

And by the way, is there any way of just retrieving specific characters from the file (in an exact position), as every line has exactly the same length?

Body:
Something like:

Dim BigGuy()
Dim numLines As Long
Arr = Split(MyFile.ReadAll, vbNewLine) ' Arr is zero-based array

numLines = UBound(Arr) + 1

ReDim BigGuy(1 To numLines, 1 To 1)

Dim I As Long
For I = 0 To numLines-1
    BigGuy(I+1, 1) = Arr(I)
Next

Range("A1").Resize(numLines, 1) = BigGuy


问:
Stopping a started background service (phantomjs) in gitlab-ci
I'm starting phantomjs with specific arguments as part of my job.

This is running on a custom gitlab/gitlab-ci server, I'm currently not using containers, I guess that would simplify that.

I'm starting phantomjs like this:

```<code>- "timeout 300 phantomjs --ssl-protocol=any --ignore-ssl-errors=true vendor/jcalderonzumba/gastonjs/src/Client/main.js 8510 1024 768 2>&1 >> /tmp/gastonjs.log &"
</code>```

Then I'm running my behat tests, and then I'm stopping that process again:

```<code>- "pkill -f 'src/Client/main.js' || true"
</code>```

The problem is when a behat test fails, then it doesn't execute the pkill and the test-run is stuck waiting on phantomjs to finish. I already added the timeout 300 but that means I'm still currently waiting 2min or so after a fail and it will eventually stop it while test are still running when they get slow enough.

I haven't found a way to run some kind of post-run/cleanup command that also runs in case of fails.

Is there a better way to do this? Can I start phantomjs in a way that gitlab-ci doesn't care that it is still running? nohup maybe?

答:
As hinted, basically my problem wasn't that I couldn't kill the process, it's that running my test script and it failing stopped at that point, resulting in a deadlock.

I was already doing something quite similar to the example from @Rufinus, but it just didn't work for me. There could be a few different things, like different way of running tests or so or starting it in before_script, which is not an option for me.

I did find a way to make it work for me, which was to prevent my test runner from stopping the execution of further tasks. I managed to do that with a "set +e" and then storing the exit code (something I tried to do before but it didn't work).

This is the relevant part from my job:

```<code># Set option to prevent gitlab from stopping if behat fails.
- set +e
- "phantomjs --ssl-protocol=any --ignore-ssl-errors=true vendor/jcalderonzumba/gastonjs/src/Client/main.js 8510 1024 768 2>&1 >> /dev/null &"
# Store the exit code.
- "./vendor/bin/behat -f progress --stop-on-failure; export TEST_BEHAT=${PIPESTATUS[0]}"
- "pkill -f 'src/Client/main.js' || true"
# Exit the build
- if [ $TEST_BEHAT -eq 0 ]; then exit 0; else exit 1; fi
</code>```

Body:
I'm starting phantomjs with specific arguments as part of my job.

This is running on a custom gitlab/gitlab-ci server, I'm currently not using containers, I guess that would simplify that.

I'm starting phantomjs like this:

- "timeout 300 phantomjs --ssl-protocol=any --ignore-ssl-errors=true vendor/jcalderonzumba/gastonjs/src/Client/main.js 8510 1024 768 2>&1 >> /tmp/gastonjs.log &"

Then I'm running my behat tests, and then I'm stopping that process again:

- "pkill -f 'src/Client/main.js' || true"

The problem is when a behat test fails, then it doesn't execute the pkill and the test-run is stuck waiting on phantomjs to finish. I already added the timeout 300 but that means I'm still currently waiting 2min or so after a fail and it will eventually stop it while test are still running when they get slow enough.

I haven't found a way to run some kind of post-run/cleanup command that also runs in case of fails.

Is there a better way to do this? Can I start phantomjs in a way that gitlab-ci doesn't care that it is still running? nohup maybe?

Body:
As hinted, basically my problem wasn't that I couldn't kill the process, it's that running my test script and it failing stopped at that point, resulting in a deadlock.

I was already doing something quite similar to the example from @Rufinus, but it just didn't work for me. There could be a few different things, like different way of running tests or so or starting it in before_script, which is not an option for me.

I did find a way to make it work for me, which was to prevent my test runner from stopping the execution of further tasks. I managed to do that with a "set +e" and then storing the exit code (something I tried to do before but it didn't work).

This is the relevant part from my job:

# Set option to prevent gitlab from stopping if behat fails.
- set +e
- "phantomjs --ssl-protocol=any --ignore-ssl-errors=true vendor/jcalderonzumba/gastonjs/src/Client/main.js 8510 1024 768 2>&1 >> /dev/null &"
# Store the exit code.
- "./vendor/bin/behat -f progress --stop-on-failure; export TEST_BEHAT=${PIPESTATUS[0]}"
- "pkill -f 'src/Client/main.js' || true"
# Exit the build
- if [ $TEST_BEHAT -eq 0 ]; then exit 0; else exit 1; fi


问:
How to stop a form from loading if a particular condition is not met?
I am on VB.NET and when the form is loading it checks if a file exists or not. If the file is found then it continues to load else it gives an error box and quits.

Something like

```<code>Public Class Form1
    Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
    Try
        Dim file As FileStream = New FileStream("target.txt", FileMode.Open, FileAccess.Read)

Catch ex As System.IO.FileNotFoundException
'code to stop form loading goes here.
End Sub
End Class
</code>```

答:
Do you mean like this?:

```<code>Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
    Try
        Dim file As FileStream = New FileStream("target.txt", FileMode.Open, FileAccess.Read)
        'the rest of your "load" code goes here...
    Catch ex As System.IO.FileNotFoundException
        MessageBox.Show("File not found", "", MessageBoxButtons.OK, MessageBoxIcon.Error)
        Close()
    End Try
End Sub
</code>```

It will show a MessageBox and close the form if the file is not found.

Body:
I am on VB.NET and when the form is loading it checks if a file exists or not. If the file is found then it continues to load else it gives an error box and quits.

Something like

Public Class Form1
    Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
    Try
        Dim file As FileStream = New FileStream("target.txt", FileMode.Open, FileAccess.Read)

Catch ex As System.IO.FileNotFoundException
'code to stop form loading goes here.
End Sub
End Class

Body:
Do you mean like this?:

Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
    Try
        Dim file As FileStream = New FileStream("target.txt", FileMode.Open, FileAccess.Read)
        'the rest of your "load" code goes here...
    Catch ex As System.IO.FileNotFoundException
        MessageBox.Show("File not found", "", MessageBoxButtons.OK, MessageBoxIcon.Error)
        Close()
    End Try
End Sub

It will show a MessageBox and close the form if the file is not found.


问:
How can i use the mouse wheel to select each time another Tool/s?
```<code>private void OnEnable()
{
    Tools.current = Tool.View;
    Tools.viewTool = ViewTool.FPS;
}
</code>```

The Tool have some properties like Rect,Scale,Rotate...
I want to use the mouse wheel up down to select between the Tool properties.

答:
If you are on an unity app, you can try this:

```<code> var d = Input.GetAxis("Mouse ScrollWheel");
 if (d > 0f)
 {
     // scroll up
 }
 else if (d < 0f)
 {
     // scroll down
 }
</code>```

source

Body:
private void OnEnable()
{
    Tools.current = Tool.View;
    Tools.viewTool = ViewTool.FPS;
}

The Tool have some properties like Rect,Scale,Rotate...
I want to use the mouse wheel up down to select between the Tool properties.

Body:
If you are on an unity app, you can try this:

 var d = Input.GetAxis("Mouse ScrollWheel");
 if (d > 0f)
 {
     // scroll up
 }
 else if (d < 0f)
 {
     // scroll down
 }

source


问:
Python gives me "None" when trying to print a function
I am quite new to python, having only toyed with it for a few days now. I am trying to cobble together a program to show off a battle system I had in mind. My issue is that I keep getting "None" produced when I try to print

```<code>import os
class Player():
    def __init__(self, name, hp, maxhp, strength, intel, charm, level):
        self.name = name
        self.hp = hp
        self.maxhp = maxhp
        self.strength = 10
        self.intel = intel
        self.charm = charm
    self.level = level
    def attack(self, Enemy):
        Enemy.hp -= self.strength

class Steve():
    def __init__(self, name, hp, maxhp, strength, intel, charm, level):
        self.name = name
        self.hp = hp
        self.maxhp = maxhp
        self.strength = strength
        self.intel = intel
    self.charm = charm
    self.level = level

class Barry():
    def __init__(self, name, hp, maxhp, strength, intel, charm, level):
        self.name = name
        self.hp = hp
        self.maxhp = maxhp
        self.strength = strength
        self.intel = intel
        self.charm = charm
        self.level = level
def Start():
    Player.hp = 100
    Player.maxhp = 200
    Player.strength = 30
    Player.intel = 10
    Player.charm = 43
    Player.level = 23
   nameSelection()

def nameSelection():
    os.system('cls')
    Player.name = input("Please enter your name\n==>")
    print("==>")
    gameStart()

def gameStart():
    os.system('cls')
    global Enemy
    print ("Player Name:",Player.name)
    print ("Who would you like to fight?")
    print ("1.)Steve")
    print ("2.)Barry")
    print ("3.)Change your name")
    option = input("==>")
    if option == "1":
        Enemy = Steve("Steve", 100, 200, 10, 20, 30, 50)
        fight()
    elif option == "2":
        Enemy = Barry("Barry", 100, 200, 10, 20, 30, 50)
        fight()
    elif option == "3":
        nameSelection()

def attack():
    Enemy.hp -= Player.strength

def fight():
    os.system('cls')
    while Enemy.hp > 0:
        os.system('cls')
        print(CharacterStats())
        print ("1.) Attack")
        print ("2.) Run")
        option = input("==>")
        if option == "1":
            attack()
            print (Enemy.hp)
    print ("You did it! You have defeated", Enemy.name,"!")
    gameStart()

def CharacterStats():
    print ("You now face", Enemy.name)
    print ("His current health is", Enemy.hp,"/",Enemy.maxhp)
    print ("His strength is", Enemy.strength)
    print ("His intelligence is", Enemy.intel)
    print ("His charm is", Enemy.charm)
    print ("He is level", Enemy.level)
Start()
</code>```

When I get to a fight encoutner with one of the two options, I get

```<code>You now face Steve
His current health is 100 / 200
His strength is 10
His intelligence is 20
His charm is 30
He is level 50
None
1.) Attack
2.) Run
==>
</code>```

I have read that return could fix it, but I can't seem to get return to give me the desired results I was looking for, both how it looks different went printed in to the player, and it only returns one of these lines of stats. I may be getting some of my terms wrong, I hope I am being clear on what my issue is.

答: As a side note, it will be more suitable if you use inheritance (use the Player class as base class eg: class Steve (Player):pass ) in your game : https://docs.python.org/2/tutorial/classes.html</p>

Body:
I am quite new to python, having only toyed with it for a few days now. I am trying to cobble together a program to show off a battle system I had in mind. My issue is that I keep getting "None" produced when I try to print

import os
class Player():
    def __init__(self, name, hp, maxhp, strength, intel, charm, level):
        self.name = name
        self.hp = hp
        self.maxhp = maxhp
        self.strength = 10
        self.intel = intel
        self.charm = charm
    self.level = level
    def attack(self, Enemy):
        Enemy.hp -= self.strength

class Steve():
    def __init__(self, name, hp, maxhp, strength, intel, charm, level):
        self.name = name
        self.hp = hp
        self.maxhp = maxhp
        self.strength = strength
        self.intel = intel
    self.charm = charm
    self.level = level

class Barry():
    def __init__(self, name, hp, maxhp, strength, intel, charm, level):
        self.name = name
        self.hp = hp
        self.maxhp = maxhp
        self.strength = strength
        self.intel = intel
        self.charm = charm
        self.level = level
def Start():
    Player.hp = 100
    Player.maxhp = 200
    Player.strength = 30
    Player.intel = 10
    Player.charm = 43
    Player.level = 23
   nameSelection()

def nameSelection():
    os.system('cls')
    Player.name = input("Please enter your name\n==>")
    print("==>")
    gameStart()

def gameStart():
    os.system('cls')
    global Enemy
    print ("Player Name:",Player.name)
    print ("Who would you like to fight?")
    print ("1.)Steve")
    print ("2.)Barry")
    print ("3.)Change your name")
    option = input("==>")
    if option == "1":
        Enemy = Steve("Steve", 100, 200, 10, 20, 30, 50)
        fight()
    elif option == "2":
        Enemy = Barry("Barry", 100, 200, 10, 20, 30, 50)
        fight()
    elif option == "3":
        nameSelection()

def attack():
    Enemy.hp -= Player.strength

def fight():
    os.system('cls')
    while Enemy.hp > 0:
        os.system('cls')
        print(CharacterStats())
        print ("1.) Attack")
        print ("2.) Run")
        option = input("==>")
        if option == "1":
            attack()
            print (Enemy.hp)
    print ("You did it! You have defeated", Enemy.name,"!")
    gameStart()

def CharacterStats():
    print ("You now face", Enemy.name)
    print ("His current health is", Enemy.hp,"/",Enemy.maxhp)
    print ("His strength is", Enemy.strength)
    print ("His intelligence is", Enemy.intel)
    print ("His charm is", Enemy.charm)
    print ("He is level", Enemy.level)
Start()

When I get to a fight encoutner with one of the two options, I get

You now face Steve
His current health is 100 / 200
His strength is 10
His intelligence is 20
His charm is 30
He is level 50
None
1.) Attack
2.) Run
==>

I have read that return could fix it, but I can't seem to get return to give me the desired results I was looking for, both how it looks different went printed in to the player, and it only returns one of these lines of stats. I may be getting some of my terms wrong, I hope I am being clear on what my issue is.


问:
Convert a Byte array to Image in c# after modifying the array
I'm trying to convert a byte[] to an image in C#. I know this question has been asked on different forums. But none of the answers given on them helped me. To give some context=
I open an image, convert it to a byte[]. I encrypt the byte[]. In the end I still have the byte[] but it has been modified ofc. Now I want to display this again. The byte[] itself consists of 6559 bytes. I try to convert it by doing :

```<code> public Image byteArrayToImage(byte[] byteArrayIn)
    {
        MemoryStream ms = new MemoryStream(byteArrayIn);
        Image returnImage = Image.FromStream(ms);
        return returnImage;
    }
</code>```

and I get this error: Parameter is not valid.

The byte array is constructed by using the .toArray() on a List

```<code>List<byte> encryptedText = new List<byte>();
pbEncrypted.Image = iConverter.byteArrayToImage(encryptedText.ToArray())
</code>```

;

Can anyone help me? Am I forgetting some kind of format or something ?

The byte that has to be converted to an image :

```<code> private void executeAlgoritm(byte[] plainText)
    {

        // Empty list of bytes
        List<byte> encryptedText = new List<byte>();

        // loop over all the bytes in the original byte array gotten from the image
        foreach (byte value in plainText)
        {
            // convert it to a bitarray
            BitArray myBits = new BitArray(8); //define the size

            for (byte x = 0; x < myBits.Count; x++)
            {
                myBits[x] = (((value >> x) & 0x01) == 0x01) ? true : false;
            }

            // encrypt the bitarray and return a byte
            byte bcipher = ConvertToByte( sdes.IPInvers(sdes.FK(sdes.Shift(sdes.FK(sdes.IP(myBits),keygen.P8(keygen.shift(keygen.P10(txtKey.Text))))),keygen.P8(keygen.shift(keygen.shift(keygen.shift(keygen.P10(txtKey.Text))))))));

            // add the byte to the list
            encryptedText.Add(bcipher);

        }
        // show the image by converting the list to an array and the array to an image
        pbEncrypted.Image = iConverter.byteArrayToImage(encryptedText.ToArray());
    }
</code>```

答: To add to @Boo's answer, you can get hold of the raw image data -- minus header -- using the Bitmap.LockBits method. There's an example of manipulating an image in this way on the MSDN page on the BitmapData class.

ContentLicense: CC BY-SA 2.5

Body:
I'm trying to convert a byte[] to an image in C#. I know this question has been asked on different forums. But none of the answers given on them helped me. To give some context=
I open an image, convert it to a byte[]. I encrypt the byte[]. In the end I still have the byte[] but it has been modified ofc. Now I want to display this again. The byte[] itself consists of 6559 bytes. I try to convert it by doing :

 public Image byteArrayToImage(byte[] byteArrayIn)
    {
        MemoryStream ms = new MemoryStream(byteArrayIn);
        Image returnImage = Image.FromStream(ms);
        return returnImage;
    }

and I get this error: Parameter is not valid.

The byte array is constructed by using the .toArray() on a List

List<byte> encryptedText = new List<byte>();
pbEncrypted.Image = iConverter.byteArrayToImage(encryptedText.ToArray())

;

Can anyone help me? Am I forgetting some kind of format or something ?

The byte that has to be converted to an image :

 private void executeAlgoritm(byte[] plainText)
    {

        // Empty list of bytes
        List<byte> encryptedText = new List<byte>();

        // loop over all the bytes in the original byte array gotten from the image
        foreach (byte value in plainText)
        {
            // convert it to a bitarray
            BitArray myBits = new BitArray(8); //define the size

            for (byte x = 0; x < myBits.Count; x++)
            {
                myBits[x] = (((value >> x) & 0x01) == 0x01) ? true : false;
            }

            // encrypt the bitarray and return a byte
            byte bcipher = ConvertToByte( sdes.IPInvers(sdes.FK(sdes.Shift(sdes.FK(sdes.IP(myBits),keygen.P8(keygen.shift(keygen.P10(txtKey.Text))))),keygen.P8(keygen.shift(keygen.shift(keygen.shift(keygen.P10(txtKey.Text))))))));

            // add the byte to the list
            encryptedText.Add(bcipher);

        }
        // show the image by converting the list to an array and the array to an image
        pbEncrypted.Image = iConverter.byteArrayToImage(encryptedText.ToArray());
    }


问:
How to detect who viewed my Telegram profile?
Is there any event in telegram API Bot or Core to detect who is viewed a user or channel or group or bot profile?

Some Bots and Apps claim that they can do this but i didn't find any programming way in the telegram API documents.

For example I just see getUserProfilePhotos method in Telegram Bot API about user profile.

Also Update objects has the following items now (in Telegram Bot):

update_id

message

edited_message

channel_post

edited_channel_post

inline_query

chosen_inline_result

callback_query

shipping_query

pre_checkout_query

答:
No method to get this data at this time.

Telegram very care about privacy, so there is no way to track users.


问:
Angular UI router permissions / access control
I am having a lot of trouble determining how to add permissions / access-control to our Angular app. Right now we have this:

```<code>    app.config(['$stateProvider', function ($stateProvider) {

      $stateProvider

      .state('default', {
        url: '',
        templateUrl: 'pages/home/view/home.html',
        controller: 'HomeCtrl'
      })

      .state('home', {
        url: '/home',
        templateUrl: 'pages/home/view/home.html',
        controller: 'HomeCtrl',

        permissions: {                    // ?
          only: ['Admin','Moderator']
        },

        access: {                         // ?
         roles: ['*']
        },

        resolve: {                        // ?
          authenticate: function($state, $q, $timeout){

          },

        }

      })

}]);
</code>```

I having trouble determining which methodology to use to create access control to each page.

Right now, the logged in user is stored in an Angular value:

```<code>app.value('USER', JSON.parse('{{{user}}}'));
</code>```

The USER value contains the information about which roles / permissions the user has.

But I cannot inject USER into app.config() callback, it says "unknown provider".

How can I do access-control based of the USER parameters?

答:
the key to perform that is to add your access control on an event $stateChangeStart

For example if you have your routing like that :

```<code>      .state('termsofuse', {
            url: "/terms",
            templateUrl: "termOfUse.html",
            resolve: {
                authorizedRoles: function() {
                    return [USER_ROLES['su'],
                        USER_ROLES['user'],
                        USER_ROLES['admin'],
                        USER_ROLES['skysu']
                    ]
                }

            }

        })
</code>```

you may define your access controle like that

```<code>.run(
            function($rootScope, $q, $location, $window, $timeout) {

                $rootScope.$on(
                    '$stateChangeStart',
                    function(event, next, current) {

                        var authorizedRoles = next.resolve.authorizedRoles();

//this function controls if user has necessary roles
                      if (!isAuthorized(authorizedRoles)) {

                            event.preventDefault();
      // and I broadcast the news                                                     $rootScope.$broadcast("AUTH_EVENTS.notAuthenticated");

                        } else {
$rootScope.$broadcast("AUTH_EVENTS.loginSuccess");

                        }

                    })

            });
</code>```

Then you just of to define your event's catcher to manager the desired behaviour (redirect / error message or whatever necessary)

Body:
I am having a lot of trouble determining how to add permissions / access-control to our Angular app. Right now we have this:

    app.config(['$stateProvider', function ($stateProvider) {

      $stateProvider

      .state('default', {
        url: '',
        templateUrl: 'pages/home/view/home.html',
        controller: 'HomeCtrl'
      })

      .state('home', {
        url: '/home',
        templateUrl: 'pages/home/view/home.html',
        controller: 'HomeCtrl',

        permissions: {                    // ?
          only: ['Admin','Moderator']
        },

        access: {                         // ?
         roles: ['*']
        },

        resolve: {                        // ?
          authenticate: function($state, $q, $timeout){

          },

        }

      })

}]);

I having trouble determining which methodology to use to create access control to each page.

Right now, the logged in user is stored in an Angular value:

app.value('USER', JSON.parse('{{{user}}}'));

The USER value contains the information about which roles / permissions the user has.

But I cannot inject USER into app.config() callback, it says "unknown provider".

How can I do access-control based of the USER parameters?

Body:
the key to perform that is to add your access control on an event $stateChangeStart

For example if you have your routing like that :

      .state('termsofuse', {
            url: "/terms",
            templateUrl: "termOfUse.html",
            resolve: {
                authorizedRoles: function() {
                    return [USER_ROLES['su'],
                        USER_ROLES['user'],
                        USER_ROLES['admin'],
                        USER_ROLES['skysu']
                    ]
                }

            }

        })

you may define your access controle like that

.run(
            function($rootScope, $q, $location, $window, $timeout) {

                $rootScope.$on(
                    '$stateChangeStart',
                    function(event, next, current) {

                        var authorizedRoles = next.resolve.authorizedRoles();

//this function controls if user has necessary roles
                      if (!isAuthorized(authorizedRoles)) {

                            event.preventDefault();
      // and I broadcast the news                                                     $rootScope.$broadcast("AUTH_EVENTS.notAuthenticated");

                        } else {
$rootScope.$broadcast("AUTH_EVENTS.loginSuccess");

                        }

                    })

            });

Then you just of to define your event's catcher to manager the desired behaviour (redirect / error message or whatever necessary)


问:
String matching on a R column
My data frame has a column on which I am trying to run string matching and then update the string upon match.I have tried couple approaches but none seemed to have work. My frame looks like the below. For column "IntNames" row 2, I would like to substitute "clin2|clin3|clin4" with only clin2 and for row3 "clin6|clin7|clin8|clin9|clin10" with only clin6. The idea is to only retain the first element for such values. I appreciate all your help and input on this.  </p>

```<code>DataFrame:

   IntNames                   values1    values2
clin1                           100        10
clin2|clin3|clin4               200         4
clin6|clin7|clin8|clin9|clin10  240         5

This is what I have written:
newIntNames <- ifelse(myFrame$IntNames=="|",myFrame$IntNames[0],myFrame$IntNames)
</code>```

答:
You can do this with sub and a regular expression.

```<code>## Replicate your data
myFrame = read.table(text="IntNames    values1 values2
clin1   100 10
clin2|clin3|clin4   200 4
clin6|clin7|clin8|clin9|clin10  240 5",
header=TRUE)

myFrame$IntNames = sub("(\\.*?)\\|.*", "\\1", myFrame$IntNames)
myFrame
  IntNames values1 values2
1    clin1     100      10
2    clin2     200       4
3    clin6     240       5
</code>```

Title: String matching on a R column

Body:
My data frame has a column on which I am trying to run string matching and then update the string upon match.I have tried couple approaches but none seemed to have work. My frame looks like the below. For column "IntNames" row 2, I would like to substitute "clin2|clin3|clin4" with only clin2 and for row3 "clin6|clin7|clin8|clin9|clin10" with only clin6. The idea is to only retain the first element for such values. I appreciate all your help and input on this.

DataFrame:

   IntNames                   values1    values2
clin1                           100        10
clin2|clin3|clin4               200         4
clin6|clin7|clin8|clin9|clin10  240         5

This is what I have written:
newIntNames <- ifelse(myFrame$IntNames=="|",myFrame$IntNames[0],myFrame$IntNames)

Body:
You can do this with sub and a regular expression.

## Replicate your data
myFrame = read.table(text="IntNames    values1 values2
clin1   100 10
clin2|clin3|clin4   200 4
clin6|clin7|clin8|clin9|clin10  240 5",
header=TRUE)

myFrame$IntNames = sub("(\\.*?)\\|.*", "\\1", myFrame$IntNames)
myFrame
  IntNames values1 values2
1    clin1     100      10
2    clin2     200       4
3    clin6     240       5


问:
POST without redirect with PHP
I have a simple form for a mailing list that I found at http://www.notonebit.com/projects/mailing-list/

The problem is when I click submit all I want it to do is display a message under the current form saying "Thanks for subscribing" without any redirect. Instead, it directs me to a completely new page.

```<code><form method="POST" action="mlml/process.php">
    <input type="text" name="address" id="email" maxlength="30" size="23">
    <input type="submit" value="" id="submit"name="submit"  >
</form>
</code>```

答:
ENGLISH Version

It seems that no one has solved this problem without javascript or ajax

You can also do the following.

Save a php file with the functions and then send them to the index of your page

Example

INDEX.PHP

```<code><div>
<?php include 'tools/edit.php';?>
<form method="post">
<input type="submit" name="disable" value="Disable" />
<input type="submit" name="enable" value="Enable" />
</form>
</div>
</code>```

Tools.php (It can be any name, note that it is kept in a folder lame tools)

```<code><?php
if(isset($_POST['enable'])) {
echo "Enable";
} else {
}

if(isset($_POST['disable'])) {
echo "Disable";
} else {
}
?>
</code>```

Title: POST without redirect with PHP

Body:
I have a simple form for a mailing list that I found at http://www.notonebit.com/projects/mailing-list/

The problem is when I click submit all I want it to do is display a message under the current form saying "Thanks for subscribing" without any redirect. Instead, it directs me to a completely new page.

<form method="POST" action="mlml/process.php">
    <input type="text" name="address" id="email" maxlength="30" size="23">
    <input type="submit" value="" id="submit"name="submit"  >
</form>

Body:
ENGLISH Version

It seems that no one has solved this problem without javascript or ajax

You can also do the following.

Save a php file with the functions and then send them to the index of your page

Example

INDEX.PHP

<div>
<?php include 'tools/edit.php';?>
<form method="post">
<input type="submit" name="disable" value="Disable" />
<input type="submit" name="enable" value="Enable" />
</form>
</div>

Tools.php (It can be any name, note that it is kept in a folder lame tools)

<?php
if(isset($_POST['enable'])) {
echo "Enable";
} else {
}

if(isset($_POST['disable'])) {
echo "Disable";
} else {
}
?>

ContentLicense: CC BY-SA 4.0


问:
Use numpy to get permutations of multiple lists' items
For example, if I have the following arrays:

```<code>arraya = ['z', 'q']
arrayb = ['t', 'f']
</code>```

I'd like to use the items from each list to create 'pairs' and get the following output:

```<code>['zt', 'zf', 'qt', 'qf']
</code>```

I know I can figure out a jury-rigged way to write a function that produces this result, but a prebuilt function would be better for my purposes.

答:
There is no builtin function for this, but you could use senderle's cartesian_product or pv's cartesian function. Which is faster may depend on your use case. Then the following yields the desired result:

```<code>In [40]: cartesian_product([['z', 'q'], ['t', 'f']]).ravel().view('<U2')
Out[40]:
array(['zt', 'zf', 'qt', 'qf'],
      dtype='<U2')
</code>```

These functions can be faster than using itertools.product. For example,

```<code>In [181]: x, y = np.arange(500), np.arange(500)

In [185]: %timeit cartesian_product([x, y])
1000 loops, best of 3: 797 µs per loop

In [184]: %timeit cartesian_product2([x, y])
1000 loops, best of 3: 1.44 ms per loop

In [186]: %timeit cartesian([x, y])
100 loops, best of 3: 4.71 ms per loop

In [100]: %timeit np.array(list(IT.product(x, y)))
10 loops, best of 3: 112 ms per loop
</code>```

Body:
For example, if I have the following arrays:

arraya = ['z', 'q']
arrayb = ['t', 'f']

I'd like to use the items from each list to create 'pairs' and get the following output:

['zt', 'zf', 'qt', 'qf']

I know I can figure out a jury-rigged way to write a function that produces this result, but a prebuilt function would be better for my purposes.

Body:
There is no builtin function for this, but you could use senderle's cartesian_product or pv's cartesian function. Which is faster may depend on your use case. Then the following yields the desired result:

In [40]: cartesian_product([['z', 'q'], ['t', 'f']]).ravel().view('<U2')
Out[40]:
array(['zt', 'zf', 'qt', 'qf'],
      dtype='<U2')

These functions can be faster than using itertools.product. For example,

In [181]: x, y = np.arange(500), np.arange(500)

In [185]: %timeit cartesian_product([x, y])
1000 loops, best of 3: 797 µs per loop

In [184]: %timeit cartesian_product2([x, y])
1000 loops, best of 3: 1.44 ms per loop

In [186]: %timeit cartesian([x, y])
100 loops, best of 3: 4.71 ms per loop

In [100]: %timeit np.array(list(IT.product(x, y)))
10 loops, best of 3: 112 ms per loop


问:
Merge two data by a similar name?
Is it possible to merge two datasets by columns with similar names?

```<code>country <- c("United States of America", "China", "Russia Federation")
scores <- c(1, 2, 3)
df.1 <- cbind(country, scores)

country <- c("United States", "China", "Russians")
scores <- c(3, 2, 1)
df.2 <- cbind(country, scores)

unsucessful.merge <- merge(df.1, df.2, by=c("country"))
unsucessful.merge
>   country scores.x scores.y
> 1   China        2        2
</code>```

As you can see, after merging, U.S. and Russia are dropped, and we are left with China. I want the data frame to look like this:

```<code>successful.merge
>                    country scores.x scores.y
> 1                    China        2        2
> 2        Russia Federation        3        1
> 3 United States of America        1        3
</code>```

答:
If you already know all the country name permutations you can use regular expressions.</p>

```<code>df.1 <- apply(df.1,2,function(x) gsub(".*United States.*|USA","United States",x,ignore.case=T))
df.1 <- apply(df.1,2,function(x) gsub(".*Russia.*","Russia",x,ignore.case=T))
df.2 <- apply(df.2,2,function(x) gsub(".*United States.*|USA","United States",x,ignore.case=T))
df.2 <- apply(df.2,2,function(x) gsub(".*Russia.*","Russia",x,ignore.case=T))
merge(df.1, df.2, by=c("country"))
        country scores.x scores.y
1         China        2        2
2        Russia        3        1
3 United States        1        3
</code>```

Title: Merge two data by a similar name?

Body:
Is it possible to merge two datasets by columns with similar names?

country <- c("United States of America", "China", "Russia Federation")
scores <- c(1, 2, 3)
df.1 <- cbind(country, scores)

country <- c("United States", "China", "Russians")
scores <- c(3, 2, 1)
df.2 <- cbind(country, scores)

unsucessful.merge <- merge(df.1, df.2, by=c("country"))
unsucessful.merge
>   country scores.x scores.y
> 1   China        2        2

As you can see, after merging, U.S. and Russia are dropped, and we are left with China. I want the data frame to look like this:

successful.merge
>                    country scores.x scores.y
> 1                    China        2        2
> 2        Russia Federation        3        1
> 3 United States of America        1        3

Body:
If you already know all the country name permutations you can use regular expressions.

df.1 <- apply(df.1,2,function(x) gsub(".*United States.*|USA","United States",x,ignore.case=T))
df.1 <- apply(df.1,2,function(x) gsub(".*Russia.*","Russia",x,ignore.case=T))
df.2 <- apply(df.2,2,function(x) gsub(".*United States.*|USA","United States",x,ignore.case=T))
df.2 <- apply(df.2,2,function(x) gsub(".*Russia.*","Russia",x,ignore.case=T))
merge(df.1, df.2, by=c("country"))
        country scores.x scores.y
1         China        2        2
2        Russia        3        1
3 United States        1        3


问:
Mouse click in non-item area of CListBox
I want to know when the user has clicked in a CListBox, but outside of any item. I was hoping to get some notification in the containing dialog so I can process the point to determine if it is inside an item via mylistbox.ItemFromPoint(flags,outside). But clicks within the listbox don't seem to result in such events. What event should I be looking for in the parent dialog, and what needs to be set up to enable it? I really don't care if it is a click or just mousedown.

My purpose for this is to deselect all items if the user clicks outside of any item, with mylistbox.SetCurSel(-1).

Addendum: This is the full code for the class implemented as suggested by @mercurydime.

(Header)

```<code>#ifndef INCLUDE_CMYLISTBOX_H
#define INCLUDE_CMYLISTBOX_H

class CMyListBox : public CListBox
{
public:

    CMyListBox();

    void                allow_deselect( bool allow = true );

protected:

    bool                m_allow_deselect;

    afx_msg void        OnLButtonDown( UINT flags, CPoint point );

    DECLARE_MESSAGE_MAP()
};

#endif  //  INCLUDE_CMYLISTBOX_H
</code>```

(Body)

```<code>#include "stdafx.h"
#include "CMyListBox.h"

CMyListBox::CMyListBox()
    : CListBox(), m_allow_deselect( false )
{
}

void CMyListBox::allow_deselect( bool allow )
{
    m_allow_deselect = allow;
}

BEGIN_MESSAGE_MAP( CMyListBox, CListBox )
    ON_WM_LBUTTONDOWN()
END_MESSAGE_MAP()

void CMyListBox::OnLButtonDown( UINT flags, CPoint point )
{
    if( m_allow_deselect )
    {
        BOOL outside( TRUE );
        ItemFromPoint( point, outside );

        if( outside )
            SetCurSel( -1 );
    }

    CListBox::OnLButtonDown( flags, point );
}
</code>```

答:
Use the Class Wizard to create a class derived from CListBox:

Ctrl+Shift+X

Click the down arrow on the Add Class button

Select the MFC Class menu item

Make sure the base class is set to CListBox

Add a message handler for WM_LBUTTONDOWN

Ctrl+Shift+X

Click the Messages tab

Double-click WM_LBUTTONDOWN

Add your ItemFromPoint code inside the handler

```<code>void CMyListBox::OnLButtonDown(UINT nFlags, CPoint point)
{
    BOOL bOutside = TRUE;
    UINT uItem = ItemFromPoint(point, bOutside);

    if (bOutside)
    {
        // do whatever
    }

    CListBox::OnLButtonDown(nFlags, point);
}
</code>```

Body:
I want to know when the user has clicked in a CListBox, but outside of any item. I was hoping to get some notification in the containing dialog so I can process the point to determine if it is inside an item via mylistbox.ItemFromPoint(flags,outside). But clicks within the listbox don't seem to result in such events. What event should I be looking for in the parent dialog, and what needs to be set up to enable it? I really don't care if it is a click or just mousedown.

My purpose for this is to deselect all items if the user clicks outside of any item, with mylistbox.SetCurSel(-1).

Addendum: This is the full code for the class implemented as suggested by @mercurydime.

(Header)

#ifndef INCLUDE_CMYLISTBOX_H
#define INCLUDE_CMYLISTBOX_H

class CMyListBox : public CListBox
{
public:

    CMyListBox();

    void                allow_deselect( bool allow = true );

protected:

    bool                m_allow_deselect;

    afx_msg void        OnLButtonDown( UINT flags, CPoint point );

    DECLARE_MESSAGE_MAP()
};

#endif  //  INCLUDE_CMYLISTBOX_H

(Body)

#include "stdafx.h"
#include "CMyListBox.h"

CMyListBox::CMyListBox()
    : CListBox(), m_allow_deselect( false )
{
}

void CMyListBox::allow_deselect( bool allow )
{
    m_allow_deselect = allow;
}

BEGIN_MESSAGE_MAP( CMyListBox, CListBox )
    ON_WM_LBUTTONDOWN()
END_MESSAGE_MAP()

void CMyListBox::OnLButtonDown( UINT flags, CPoint point )
{
    if( m_allow_deselect )
    {
        BOOL outside( TRUE );
        ItemFromPoint( point, outside );

        if( outside )
            SetCurSel( -1 );
    }

    CListBox::OnLButtonDown( flags, point );
}

Body:
Use the Class Wizard to create a class derived from CListBox:

Ctrl+Shift+X

Click the down arrow on the Add Class button

Select the MFC Class menu item

Make sure the base class is set to CListBox

Add a message handler for WM_LBUTTONDOWN

Ctrl+Shift+X

Click the Messages tab

Double-click WM_LBUTTONDOWN

Add your ItemFromPoint code inside the handler

void CMyListBox::OnLButtonDown(UINT nFlags, CPoint point)
{
    BOOL bOutside = TRUE;
    UINT uItem = ItemFromPoint(point, bOutside);

    if (bOutside)
    {
        // do whatever
    }

    CListBox::OnLButtonDown(nFlags, point);
}


问:
BigQuery standard SQL table wildcards with date columns
I'm getting an error when using a date column in the BigQuery web UI, with a query in standard SQL, when using table wildcards.

This works:

```<code>#standardSQL
SELECT
  sale_item,
  date_of_sale
FROM `my-project.past_sales.sales_20170601`
limit 100
</code>```

This does not:

```<code>#standardSQL
SELECT
  sale_item,
  date_of_sale
FROM `my-project.past_sales.sales_*`
WHERE _TABLE_SUFFIX BETWEEN "20170530" AND "20170601"
limit 100
</code>```

The column date_of_sale is type DATE, while sale_item is type STRING.  The error is: Error: Invalid adaptation for field: date_of_sale (message Msg_0_CLOUD_QUERY_TABLE). Cannot change from TYPE_STRING to int32

答:
This means that date_of_sale is a DATE in one table and a STRING in another. You can find the culprit by taking a union instead:

```<code>#standardSQL
SELECT * FROM `my-project.past_sales.sales_20170530` UNION ALL
SELECT * FROM `my-project.past_sales.sales_20170531` UNION ALL
SELECT * FROM `my-project.past_sales.sales_20170601`;
</code>```

You don't actually need to run the query; the validator in the UI will indicate where the mismatched column type is.

To fix the error, you can either regenerate the data for the problematic day, applying a cast, or you can run a query with a union instead where you add an explicit cast. For example, supposing that the table for 20170531 has the column as a STRING, you could do:

```<code>#standardSQL
SELECT
  sale_item,
  date_of_sale
FROM (
  SELECT *
  FROM `my-project.past_sales.sales_*`
  WHERE _TABLE_SUFFIX BETWEEN "20170530" AND "20170601" AND
    _TABLE_SUFFIX != 20170531
) UNION ALL
SELECT * REPLACE(CAST(date_of_sale AS DATE) AS date_of_sale)
FROM `my-project.past_sales.sales_20170531`
LIMIT 100;
</code>```

Body:
I'm getting an error when using a date column in the BigQuery web UI, with a query in standard SQL, when using table wildcards.

This works:

#standardSQL
SELECT
  sale_item,
  date_of_sale
FROM `my-project.past_sales.sales_20170601`
limit 100

This does not:

#standardSQL
SELECT
  sale_item,
  date_of_sale
FROM `my-project.past_sales.sales_*`
WHERE _TABLE_SUFFIX BETWEEN "20170530" AND "20170601"
limit 100

The column date_of_sale is type DATE, while sale_item is type STRING.  The error is: Error: Invalid adaptation for field: date_of_sale (message Msg_0_CLOUD_QUERY_TABLE). Cannot change from TYPE_STRING to int32

Body:
This means that date_of_sale is a DATE in one table and a STRING in another. You can find the culprit by taking a union instead:

#standardSQL
SELECT * FROM `my-project.past_sales.sales_20170530` UNION ALL
SELECT * FROM `my-project.past_sales.sales_20170531` UNION ALL
SELECT * FROM `my-project.past_sales.sales_20170601`;

You don't actually need to run the query; the validator in the UI will indicate where the mismatched column type is.

To fix the error, you can either regenerate the data for the problematic day, applying a cast, or you can run a query with a union instead where you add an explicit cast. For example, supposing that the table for 20170531 has the column as a STRING, you could do:

#standardSQL
SELECT
  sale_item,
  date_of_sale
FROM (
  SELECT *
  FROM `my-project.past_sales.sales_*`
  WHERE _TABLE_SUFFIX BETWEEN "20170530" AND "20170601" AND
    _TABLE_SUFFIX != 20170531
) UNION ALL
SELECT * REPLACE(CAST(date_of_sale AS DATE) AS date_of_sale)
FROM `my-project.past_sales.sales_20170531`
LIMIT 100;


问:
SEO URL # vs. #!

Possible Duplicate:

  What's the shebang (#!) in Facebook and new Twitter URLs for?

Hello!

What is the difference between this URL: mysite.com/images.php#img-1 and this URL: mysite.com/images.php#!img-1, please?

I have a simple photo gallery, nothing fancy, that changes images from a JavaScript array of files and instead of refreshing the page for every image it does it "on the spot" using jQuery.

Thank you.

答:
It is for "Ajax Crawling"

If you're running an AJAX application with content that you'd like to appear in search results, we have a new process that, when implemented, can help Google (and potentially other search engines) crawl and index your content. Historically, AJAX applications have been difficult for search engines to process because AJAX content is produced dynamically by the browser and thus not visible to crawlers. While there are existing methods for dealing with this problem, they involve regular manual maintenance to keep the content up-to-date.

and

Indicate to the crawler that your site supports the AJAX crawling scheme

  The first step to getting your AJAX site indexed is to indicate to the crawler that your site supports the AJAX crawling scheme. The way to do this is to use a special token in your hash fragments (that is, everything after the # sign in a URL): hash fragments have to begin with an exclamation mark. For example, if your AJAX app contains a URL like this:

Title: SEO URL # vs. #!


问:
Getting two unique results from same row using Hibernate Criteria
Is it possible to get two unique results from the same table using Hibernate Criteria? For instance, what if I'd like to query the most recent type of vehicle (a truck or a car).

```<code>Criteria criteria = getCurrentSession().createCriteria(Vehicle.class);
criteria.add(Restrictions.eq("vehicleType", "car"));  // notice how I want a unique car AND truck
criteria.add(Restrictions.eq("vehicleType", "truck"));
criteria.add(Restrictions.le("date", date));
criteria.addOrder(Order.desc("date"));
criteria.setMaxResults(2);
Object result = criteria.uniqueResult(); // Possible to get most recent unique car and truck?
</code>```

I'd like to do this in one query because I assume one query to the database will be faster than two queries to the database.

So to rephrase my question, how can I get the most recent car and the most recent truck in one Hibernate Criteria Query. Assume that car and truck are represented as decimals so the table can be sorted by vehicleType.

To be even more specific, I'd like to do this using hibernate.

答:
In the end I found out that I can make a native SQL Query using Hibernate.

For example:

```<code>getCurrentSession().createSQLQuery("SELECT * FROM Vehicle").list();
</code>```

The downside to this is that Hibernate returns an Object[] instead of the an Object of type Vehicle (in the example above).

Body:
Is it possible to get two unique results from the same table using Hibernate Criteria? For instance, what if I'd like to query the most recent type of vehicle (a truck or a car).

Criteria criteria = getCurrentSession().createCriteria(Vehicle.class);
criteria.add(Restrictions.eq("vehicleType", "car"));  // notice how I want a unique car AND truck
criteria.add(Restrictions.eq("vehicleType", "truck"));
criteria.add(Restrictions.le("date", date));
criteria.addOrder(Order.desc("date"));
criteria.setMaxResults(2);
Object result = criteria.uniqueResult(); // Possible to get most recent unique car and truck?

I'd like to do this in one query because I assume one query to the database will be faster than two queries to the database.

So to rephrase my question, how can I get the most recent car and the most recent truck in one Hibernate Criteria Query. Assume that car and truck are represented as decimals so the table can be sorted by vehicleType.

To be even more specific, I'd like to do this using hibernate.

Body:
In the end I found out that I can make a native SQL Query using Hibernate.

For example:

getCurrentSession().createSQLQuery("SELECT * FROM Vehicle").list();

The downside to this is that Hibernate returns an Object[] instead of the an Object of type Vehicle (in the example above).


问:
Closing or swapping the Standard Editor in Xcode
In Xcode, when editing Swift or other files, it is possible to open one file in the Standard Editor and another file in the Assistant Editor.  The Assistant Editor can be closed leaving the Standard Editor open.

Two questions:

Is it possible to close the Standard Editor and leave the Assistant Editor open.  (In effect making the Assistant Editor into the Standard Editor.)

Is it possible to swap files between the Standard and Assistant Editors?

答:
As far as I know you cannot close the Standard (main) editor.

You can

Swap the files between the two editors

but you need a few steps to accomplish that. There's no button or single shortcut to accomplish that (or at least none that I am aware of).

This is how you do it (A = Standard Editor, B = Assistant Editor – or vice versa!):

Load the file from A in B.

⌥⌘,

Go one step back in the history of B, but open that file in A.

^⌥⌘←

You'll need to change the focus between step 1 and 2 by either clicking on the other editor or using another shortcut.

Here's the answer to a similar question that explains it and provides more information for the case when you have multiple assistant editors open.


问:
Binary string to unicode
I'm not 100% sure why my binary string to unicode isn't working..can anyone point out the issue or help me patch it? Also the reason why i chunk out the binary is that it is too large for ParseInt to handle.  See the playground link below for an example.

```<code>func binToString(s []byte) string {
    var counter int
    chunk := make([]byte, 7)
    var buf bytes.Buffer
    for i := range s {
        if i%8 == 0 {
            counter = 0
            if i, err := strconv.ParseInt(string(chunk), 2, 64); err == nil {
                buf.WriteString(string(i))
            }
        } else {
            chunk[counter] = s[i] //i know i can use modulus here too but i was testing and an counter was easier to track and test for me
            counter++
        }
    }
    return buf.String()
}
</code>```

It either seems to miss a character or add an character (or two) on conversion.

Here is a playground link showing an example of the function not working as expected.

答:
Your function could be implemented in a simpler, more efficient manner:

```<code>func binToString(s []byte) string {
    output := make([]byte, len(s)/8)
    for i := 0; i < len(output); i++ {
        val, err := strconv.ParseInt(string(s[i*8:(i+1)*8]), 2, 64)
        if err == nil {
            output[i] = byte(val)
        }
    }
    return string(output)
}
</code>```

https://play.golang.org/p/Fmo7I-rN3c

Title: Binary string to unicode

Body:
I'm not 100% sure why my binary string to unicode isn't working..can anyone point out the issue or help me patch it? Also the reason why i chunk out the binary is that it is too large for ParseInt to handle.  See the playground link below for an example.

func binToString(s []byte) string {
    var counter int
    chunk := make([]byte, 7)
    var buf bytes.Buffer
    for i := range s {
        if i%8 == 0 {
            counter = 0
            if i, err := strconv.ParseInt(string(chunk), 2, 64); err == nil {
                buf.WriteString(string(i))
            }
        } else {
            chunk[counter] = s[i] //i know i can use modulus here too but i was testing and an counter was easier to track and test for me
            counter++
        }
    }
    return buf.String()
}

It either seems to miss a character or add an character (or two) on conversion.

Here is a playground link showing an example of the function not working as expected.

Body:
Your function could be implemented in a simpler, more efficient manner:

func binToString(s []byte) string {
    output := make([]byte, len(s)/8)
    for i := 0; i < len(output); i++ {
        val, err := strconv.ParseInt(string(s[i*8:(i+1)*8]), 2, 64)
        if err == nil {
            output[i] = byte(val)
        }
    }
    return string(output)
}

https://play.golang.org/p/Fmo7I-rN3c


问:
Animate certain elements out on page change
So I have been reading into page transitions and they get very complex very quickly. I am still new to jQuery so I was hoping to get a simplified answer as to how to execute animations (namely on individual elements) on page transitions.

I apologise for how basic these questions are but as I am sure you all know, once you grasp the basic fundamentals and their simplistic concepts it makes the rest a whole lot easier.

So from what I have read, you would use jQuery to detect the page change, execute the animation then allow for the change of page.

Then jQuery would execute on page load and animate the elements in.

Question 1:
So for the first part, I have figured out that I would need to use:

```<code>$( window ).unload(function() {
  return "Handler for .unload() called.";
});
</code>```

How would I use this to delay the change of page long enough to complete my animations, and would this account for page changes using the back and forward browser buttons?

Question 2:
How would I make sure my elements start off screen when the new page is loading and only animate in once the content has been loaded?

The $(document).ready function will only execute once the page is ready and thus will show the logo on screen and the jump it off screen and animate it back on.

P.s I will update this thread with detailed steps on how I get to my desired result once I figure it all out. Massive thanks.

答:
For your first question, you can try out the following jquery code.

```<code>$(window).load(function() {
    $(".animation").fadeOut("slow").delay(1000);
});
</code>```

The above animation will load as soon as the page is loaded. You can also add .delay() if you would like to add an additional delay :)

Body:
So I have been reading into page transitions and they get very complex very quickly. I am still new to jQuery so I was hoping to get a simplified answer as to how to execute animations (namely on individual elements) on page transitions.

I apologise for how basic these questions are but as I am sure you all know, once you grasp the basic fundamentals and their simplistic concepts it makes the rest a whole lot easier.

So from what I have read, you would use jQuery to detect the page change, execute the animation then allow for the change of page.

Then jQuery would execute on page load and animate the elements in.

Question 1:
So for the first part, I have figured out that I would need to use:

$( window ).unload(function() {
  return "Handler for .unload() called.";
});

How would I use this to delay the change of page long enough to complete my animations, and would this account for page changes using the back and forward browser buttons?

Question 2:
How would I make sure my elements start off screen when the new page is loading and only animate in once the content has been loaded?

The $(document).ready function will only execute once the page is ready and thus will show the logo on screen and the jump it off screen and animate it back on.

P.s I will update this thread with detailed steps on how I get to my desired result once I figure it all out. Massive thanks.

Body:
For your first question, you can try out the following jquery code.

$(window).load(function() {
    $(".animation").fadeOut("slow").delay(1000);
});

The above animation will load as soon as the page is loaded. You can also add .delay() if you would like to add an additional delay :)


答:
Aside from css tricks, you could use Math.sin with interval, apply this to Bezier Curve (loop & join into attribute string) and it's done.

function anim(){
 document.querySelectorAll('svg circle').forEach((c,i)=>c.setAttribute('cy',50+Math.sin(performance.now()/1000+i)*25))
}
setInterval(anim,20)```
<pre class="snippet-code-html lang-html prettyprint-override"><code><svg id="wave" version="1.1" id="Layer_1" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" x="0px" y="0px"
     viewBox="0 0 456 100" style="enable-background:new 0 0 456 100;" xml:space="preserve">
<style type="text/css">
    .st69{fill:none;stroke:#000000;stroke-width:12;stroke-miterlimit:10;}
</style>
    <circle cx="50" cy="50" r="4"  fill="red" />
    <circle cx="100" cy="50" r="4"  fill="red" />
    <circle cx="150" cy="50" r="4"  fill="red" />
    <circle cx="200" cy="50" r="4" fill="red" />
    <circle cx="250" cy="50" r="4"  fill="red" />
    <circle cx="300" cy="50" r="4"  fill="red" />
    <circle cx="350" cy="50" r="4"  fill="red" />
    <circle cx="400" cy="50" r="4" fill="red" />
</svg></code>```

Title: Continuous wave like animation from wave line svg

Body:
Hello I have an svg that is a wavy line built with adobe illustrator and I'm trying to add a continuous wave like animation to it.

I've tried vivus.js and was able to get the draw animation working but not coninuously.

Does anyone have an idea on how to start something like this? I don't expect someone to do the problem for me but instead point me to the right direction, although im not opposed if someone has a quick answer.

Any answer will work wether its pure css, js or both.

Here is the svg

<svg id="wave" version="1.1" id="Layer_1" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" x="0px" y="0px"
     viewBox="0 0 456.7 39.9" style="enable-background:new 0 0 456.7 39.9;" xml:space="preserve">

    <path class="st69" d="M4.2,33.2c0.1-0.1,7-6.9,15.9-13.8C27.7,13.7,38.7,6,47.5,6c7.5,0,14,6.6,20.3,12.9l0.4,0.4
    c6.8,6.9,14.6,14.6,24.6,14.6c9.9,0,17.7-7.8,24.5-14.6l0.5-0.5C124,12.5,130.5,6,137.9,6c7.5,0,13.9,6.5,20.2,12.9l0.4,0.4
    c6.8,6.9,14.6,14.6,24.5,14.6c10,0,17.8-7.8,24.6-14.6l0.5-0.5C214.4,12.5,220.9,6,228.4,6c7.5,0,14,6.5,20.2,12.9l0.4,0.4
    c6.8,6.9,14.5,14.6,24.5,14.6c9.9,0,17.7-7.8,24.5-14.6l0.3-0.3c6.3-6.4,12.9-13,20.5-13c7.5,0,14.1,6.6,20.4,13l0.3,0.3
    c6.8,6.9,14.6,14.6,24.5,14.6c9.9,0,17.6-7.8,24.5-14.6l0.2-0.2C395.1,12.6,401.6,6,409.2,6c8.7,0,19.8,7.7,27.3,13.4
    c8.9,6.8,15.9,13.7,16,13.8"/>
</svg>

and the jsfiddle link

here

Thanks!!

Body:
Aside from css tricks, you could use Math.sin with interval, apply this to Bezier Curve (loop & join into attribute string) and it's done.

function anim(){
 document.querySelectorAll('svg circle').forEach((c,i)=>c.setAttribute('cy',50+Math.sin(performance.now()/1000+i)*25))
}
setInterval(anim,20)

<svg id="wave" version="1.1" id="Layer_1" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" x="0px" y="0px"
     viewBox="0 0 456 100" style="enable-background:new 0 0 456 100;" xml:space="preserve">
<style type="text/css">
    .st69{fill:none;stroke:#000000;stroke-width:12;stroke-miterlimit:10;}
</style>
    <circle cx="50" cy="50" r="4"  fill="red" />
    <circle cx="100" cy="50" r="4"  fill="red" />
    <circle cx="150" cy="50" r="4"  fill="red" />
    <circle cx="200" cy="50" r="4" fill="red" />
    <circle cx="250" cy="50" r="4"  fill="red" />
    <circle cx="300" cy="50" r="4"  fill="red" />
    <circle cx="350" cy="50" r="4"  fill="red" />
    <circle cx="400" cy="50" r="4" fill="red" />
</svg>


问:
C# creating ".exe" with libraries
I'm using some dlls in my project. To make a '.exe' file i only used 'Released' in Solution Configurations. In my computer exe file works, but in another there's an error: "Can't load file X...". X is a dll file. How can i solve this problem? I copied all dlls into project-bin-realese.</p>

答: The above answers are generic for loading dependency libraries. However, it may also depend on how the exe loading the libraries. For example, MEF has a DI engine to load catalog libraries from a specific folder. If the required libraries are not there, you may get similar exception. Check your .exe requirement for its specific dependencies.</p>

Title: C# creating ".exe" with libraries


问:
SQL Server Update statement to change year and month of a datetime column
I want to update the TimeOccurred column in all tables in a database (also fine with doing 1 table at a time if that is necessary). This is what the current values in this column look like:

```<code>2017-06-12 14:34:00
</code>```

I would like to replace that value in all tables in the column TimeOccurred by changing just the year to the current year and the month to the previous month.

So 2012-03-14 14:34:00 becomes 2017-05-14 14:34:00.

It would also help if I could check the day and if it was 29,30,or 31 change it to 25.

Update:

It's -1 month based on the current right now month. We want to change the days in case the month ends up being February, we can't have an event happening on February 31st for example. So all events should be days 1-28 to be safe.

More sample data:

```<code>2014-07-28 13:03:00
2012-07-28 13:03:00
2015-07-28 13:03:00
2014-07-28 13:03:00
2015-07-28 13:03:00
2016-07-29 11:02:00
2013-07-29 11:07:00
2005-07-29 11:12:00
2010-07-29 14:37:00
2015-07-29 14:37:00
2015-07-29 14:37:00
2015-07-29 14:37:00
2015-07-29 14:37:00
2015-07-29 14:37:00
2015-07-29 14:37:00
2015-07-29 14:37:00
2015-07-29 14:37:00
2015-07-29 14:37:00
2015-07-29 14:37:00
2015-07-29 14:37:00
</code>```

Body:
I want to update the TimeOccurred column in all tables in a database (also fine with doing 1 table at a time if that is necessary). This is what the current values in this column look like:

2017-06-12 14:34:00

I would like to replace that value in all tables in the column TimeOccurred by changing just the year to the current year and the month to the previous month.

So 2012-03-14 14:34:00 becomes 2017-05-14 14:34:00.

It would also help if I could check the day and if it was 29,30,or 31 change it to 25.

Update:

It's -1 month based on the current right now month. We want to change the days in case the month ends up being February, we can't have an event happening on February 31st for example. So all events should be days 1-28 to be safe.

More sample data:

2014-07-28 13:03:00
2012-07-28 13:03:00
2015-07-28 13:03:00
2014-07-28 13:03:00
2015-07-28 13:03:00
2016-07-29 11:02:00
2013-07-29 11:07:00
2005-07-29 11:12:00
2010-07-29 14:37:00
2015-07-29 14:37:00
2015-07-29 14:37:00
2015-07-29 14:37:00
2015-07-29 14:37:00
2015-07-29 14:37:00
2015-07-29 14:37:00
2015-07-29 14:37:00
2015-07-29 14:37:00
2015-07-29 14:37:00
2015-07-29 14:37:00
2015-07-29 14:37:00

Body:
Try this, just replace your_table_name with each table you want to apply this to.

UPDATE your_table_name
SET TimeOccurred =
    CAST( CAST( DATEPART( YEAR, GETDATE() ) AS VARCHAR( 4 ) ) + '-' +
         CAST( DATEPART( MONTH, DATEADD( MONTH, -1, GETDATE() ) ) AS VARCHAR( 2 ) ) + '-' +
         (CASE
            WHEN DATEPART( DAY, TimeOccurred ) IN ( 29, 30, 31 )
            THEN '25'
            ELSE CAST( DATEPART( DAY, TimeOccurred ) AS VARCHAR( 2 ) )
         END) +
         RIGHT( TimeOccurred, 8 )
     AS SMALLDATETIME )

Output:

+---------------------+
|    TimeOccurred     |
+---------------------+
| 2017-05-28 13:03:00 |
| 2017-05-28 13:03:00 |
| 2017-05-28 13:03:00 |
| 2017-05-28 13:03:00 |
| 2017-05-28 13:03:00 |
| 2017-05-25 11:02:00 |
| 2017-05-25 11:07:00 |
| 2017-05-25 11:12:00 |
| 2017-05-25 14:37:00 |
| 2017-05-25 14:37:00 |
| 2017-05-25 14:37:00 |
| 2017-05-25 14:37:00 |
| 2017-05-25 14:37:00 |
| 2017-05-25 14:37:00 |
| 2017-05-25 14:37:00 |
| 2017-05-25 14:37:00 |
| 2017-05-25 14:37:00 |
| 2017-05-25 14:37:00 |
| 2017-05-25 14:37:00 |
| 2017-05-25 14:37:00 |
+---------------------+

Demo:
Rextester Demo


问:
Setting the 'outDir' attribute in Visual Studio Code
I continue to get this error when I attempt to debug a C++ program: can't launch program 'c:\Users\'my username'\Desktop\C++\'; setting the 'outDir' attribute might help

I have tried various combinations of syntax so that it would satisfy the condition, but I have had no success. I have spent hours trying to find the proper syntax and I have no idea what my problem is. I have had success with running JavaScript applications but they don't seem to require Source maps or the outDir field to be filled. I have the latest version of Visual Studio Code which is 0.7.10 and I have node downloaded and it seems to work fine. Here is a screenshot so you can get an idea of what I'm seeing. http://i.imgur.com/wIcVoQz.png

答:
The VSCode message Cannot launch program ... setting the 'outDir' attribute might help can be somewhat misleading, even as recently as VSCode v1.12.2.  I would take it with a grain of salt, it seems to simply mean there was a problem launching the application.

In my case, it was caused by a minor error in my launch.json file.   I had:

```<code>        "type": "node",
        "request": "launch",
        "name": "Gulp",
        "program": "${workspaceRoot}/node_modules/gulp/bin",
        "sourceMaps": true,
        "outFiles": [
            "${workspaceRoot}/{lib,node_modules}/**/*.js",
            "!${workspaceRoot}/lib/tests/**/*.js"
        ]
</code>```

I fixed it by changing one line:

```<code>        "program": "${workspaceRoot}/node_modules/gulp/bin/gulp",
</code>```

Despite the message's attempt to be helpful, the outFiles property may not be necessary or helpful.   Once I fixed the other problem, debugging seems to work fine without it.

Filed as a vscode issue 6/8/2017

Body:
The VSCode message Cannot launch program ... setting the 'outDir' attribute might help can be somewhat misleading, even as recently as VSCode v1.12.2.  I would take it with a grain of salt, it seems to simply mean there was a problem launching the application.

In my case, it was caused by a minor error in my launch.json file.   I had:

        "type": "node",
        "request": "launch",
        "name": "Gulp",
        "program": "${workspaceRoot}/node_modules/gulp/bin",
        "sourceMaps": true,
        "outFiles": [
            "${workspaceRoot}/{lib,node_modules}/**/*.js",
            "!${workspaceRoot}/lib/tests/**/*.js"
        ]

I fixed it by changing one line:

        "program": "${workspaceRoot}/node_modules/gulp/bin/gulp",

Despite the message's attempt to be helpful, the outFiles property may not be necessary or helpful.   Once I fixed the other problem, debugging seems to work fine without it.

Filed as a vscode issue 6/8/2017


问:
Multiple Date Ranges in a Single Tablea Date Table
I am trying to display Daily,Weekly,Monthly,Yearly data in a single Tableau data table. The base calculation is attach rate (sum(a)/sum(b)).

My main challenge is figuring out how to create a single table with multiple date ranges.

答:
From your question it is not completely clear what you mean by daily, monthly, etc.

In any way you can do it by creating multiple calculated fields

If you want the average daily, monthly, devide the sum of your measure by the datediff between your two dates in days, months, etc. You might have to use {fixed} formulas to get the min and max date in order to get the days in between. That depends on your data structure.

If you want to show a measure for the last day, last week, last month, create an formula that outputs the measure if the the date is yesterday, within the last week, within the last month.
here an example for the weekly sum:

```<code>IF datediff('days', [date], today()) < 7 THEN [measure] END
</code>```

If that's not what you need, I would need some details as to how your data looks like and what exactly you want to display. Ideally a mockup of some sort.

Body:
From your question it is not completely clear what you mean by daily, monthly, etc.

In any way you can do it by creating multiple calculated fields

If you want the average daily, monthly, devide the sum of your measure by the datediff between your two dates in days, months, etc. You might have to use {fixed} formulas to get the min and max date in order to get the days in between. That depends on your data structure.

If you want to show a measure for the last day, last week, last month, create an formula that outputs the measure if the the date is yesterday, within the last week, within the last month.
here an example for the weekly sum:

IF datediff('days', [date], today()) < 7 THEN [measure] END

If that's not what you need, I would need some details as to how your data looks like and what exactly you want to display. Ideally a mockup of some sort.


问:
DestroyWindow does not close window on Mac using Python and OpenCV
My program generates a series of windows using the following code:

```<code>def display(img, name, fun):
    global clicked

    cv.NamedWindow(name, 1)
    cv.ShowImage(name, img)
    cv.SetMouseCallback(name, fun, img)

    while cv.WaitKey(33) == -1:
        if clicked == 1:
            clicked = 0
            cv.ShowImage(name, img)

    cv.DestroyWindow(name)
</code>```

I press "q" within the gui window to close it. However, the code continues to the next call of the display function and displays a second gui window while not closing the first. I'm using a Mac with OpenCV 2.1, running the program in Terminal. How can I close the gui windows? Thanks.

答:
Here is what worked for me:
</p>

```<code>cv2.namedWindow("image")
cv2.imshow('image', img)
cv2.waitKey(0) # close window when a key press is detected
cv2.destroyWindow('image')
cv2.waitKey(1)
</code>```

Body:
My program generates a series of windows using the following code:

def display(img, name, fun):
    global clicked

    cv.NamedWindow(name, 1)
    cv.ShowImage(name, img)
    cv.SetMouseCallback(name, fun, img)

    while cv.WaitKey(33) == -1:
        if clicked == 1:
            clicked = 0
            cv.ShowImage(name, img)

    cv.DestroyWindow(name)

I press "q" within the gui window to close it. However, the code continues to the next call of the display function and displays a second gui window while not closing the first. I'm using a Mac with OpenCV 2.1, running the program in Terminal. How can I close the gui windows? Thanks.

Body:
Here is what worked for me:

cv2.namedWindow("image")
cv2.imshow('image', img)
cv2.waitKey(0) # close window when a key press is detected
cv2.destroyWindow('image')
cv2.waitKey(1)


问:
document.onmousemove delay
I'm trying to build an expensive script with mouse and keyboard control on canvas.
I'm using document.onmousemove and document.onkeydown/onkeyup to do this control, but when i press any button, i've got a lot of "onkeydown" executions, and mouse lags terribly. It looks like "write-only mouse position buffer" or something. When i release the key, mouse "simulate" my earlier moves.
I tested it on Firefox and chrome, this problem exist only on FF.

here is some code

```<code>    document.onmousemove  = function(e){
        obj = canvas;
        var curleft = curtop = 0;

        do {
            curleft += obj.offsetLeft;
            curtop += obj.offsetTop;
        } while (obj = obj.offsetParent);

        mX = e.pageX - curleft;
        mY = e.pageY - curtop;
    }

    var dt=0.02;
    setInterval(tick, dt*1000);
    update(dt);
    function tick() {

        if((!pause) || step)
        {
            update(dt);
            step = false;
        }
        interact();
        draw();
    }
</code>```

答:
Depending on how complex your update, interact and draw functions are, your timer interval of 20 ms may be too short and taking up a lot of CPU time. Since JavaScript runs in a single thread, this can prevent your script from processing the mouse events.

These events can queue up in the browser's input queue and be dispatched to your script later (which is probably happening in Firefox) or they may be discarded if your script doesn't process them quickly enough (which might be happening in Chrome).

Some possible workarounds:

Increase the timer interval.

Instead of using setInterval, try using setTimeout after each execution of tick -- this will prevent multiple timer events from queuing up and firing together.

Title: document.onmousemove delay

Body:
I'm trying to build an expensive script with mouse and keyboard control on canvas.
I'm using document.onmousemove and document.onkeydown/onkeyup to do this control, but when i press any button, i've got a lot of "onkeydown" executions, and mouse lags terribly. It looks like "write-only mouse position buffer" or something. When i release the key, mouse "simulate" my earlier moves.
I tested it on Firefox and chrome, this problem exist only on FF.

here is some code

    document.onmousemove  = function(e){
        obj = canvas;
        var curleft = curtop = 0;

        do {
            curleft += obj.offsetLeft;
            curtop += obj.offsetTop;
        } while (obj = obj.offsetParent);

        mX = e.pageX - curleft;
        mY = e.pageY - curtop;
    }

    var dt=0.02;
    setInterval(tick, dt*1000);
    update(dt);
    function tick() {

        if((!pause) || step)
        {
            update(dt);
            step = false;
        }
        interact();
        draw();
    }


问:
How I can limit the border of tooltip in jquery?
Hello I am using tooltip with codemirror , what I want is to make the border of tooltip not out of  the border of the editor  ... see to this link to show how the border of tooltip  out of the border of the editor jsbin

this is the code :
css:

```<code>.tooltip{background:red;z-index:1000;}
</code>```

script:

```<code>var cm = CodeMirror(document.getElementById("editor"), {
    value: "function myScript() {\n    return 100;\n}",
    mode: "javascript",
    indentUnit: 4,
    lineNumbers: true,

});

var textMarker;

$('#add').click(function() {
    textMarker = cm.markText({
        line: 1,
        ch: 4
    }, {
        line: 1,
        ch: 10
    }, {
        className: 'marked-text'
    });

    $('.marked-text').tooltip({
        title: 'This is a return statement sfdl glrflg rgmlf',
        container: 'body',
        delay: { "show": 500, "hide": 100 },
        animation: false
    });
});

$('#remove').click(function() {
    if (textMarker) {
        textMarker.clear();
    }
});
</code>```

How I can solve this problem ?

Note : I want to title of tooltip appare at all , so the panding 0 can not solve the problem

答:
I've added 0 padding to your css code.

```<code>html, body {
  padding: 0;
}
</code>```

Is this what you wanted to achieve?

Body:
Hello I am using tooltip with codemirror , what I want is to make the border of tooltip not out of  the border of the editor  ... see to this link to show how the border of tooltip  out of the border of the editor jsbin

this is the code :
css:

.tooltip{background:red;z-index:1000;}

script:

var cm = CodeMirror(document.getElementById("editor"), {
    value: "function myScript() {\n    return 100;\n}",
    mode: "javascript",
    indentUnit: 4,
    lineNumbers: true,

});

var textMarker;

$('#add').click(function() {
    textMarker = cm.markText({
        line: 1,
        ch: 4
    }, {
        line: 1,
        ch: 10
    }, {
        className: 'marked-text'
    });

    $('.marked-text').tooltip({
        title: 'This is a return statement sfdl glrflg rgmlf',
        container: 'body',
        delay: { "show": 500, "hide": 100 },
        animation: false
    });
});

$('#remove').click(function() {
    if (textMarker) {
        textMarker.clear();
    }
});

How I can solve this problem ?

Note : I want to title of tooltip appare at all , so the panding 0 can not solve the problem

Body:
I've added 0 padding to your css code.

html, body {
  padding: 0;
}

Is this what you wanted to achieve?


问:
moving file from one location to another without knowing file name
One of my executable process produces two files. I want to move one file that is produced to shared drive. I am writing an automatic process to move the file from one location to shared drive. The only issue is file name changes every time the executable is run so I don't have the exact filename with me. I only have the extension, .xls. I have only one .xls file in my directory.

I tried doing this

```<code>File.Copy(@"*.xls", @"\\serv44\Application\testing\name\test2\*.xls", true);
</code>```

It threw an error saying Invalid name. After moving the file to shared drive. I want to delete the .xls file.

```<code>File.Delete("*.xls");
</code>```

any help will be appreciated

答:
You should get file name and then do whatever you want with that file. I.e. if you have only one xls file in the source directory:

```<code>var targetDirectory = @"\\serv44\Application\testing\name\test2\";
var sourceFile = Directory.EnumerateFiles(sourceDirectory, "*.xls").FirstOrDefault();
if (sourceFile != null)
{
    var sourceFileName = Path.GetFileName(sourceFile);
    var targetFileName = Path.Combine(targetDirectory, sourceFileName);
    File.Copy(sourceFileName, targetFileName);
    File.Delete(sourceFileName);
}
</code>```

Note: instead of copy and delete you can use single Move operation.

If you want to move several files from your source directory, then instead of taking first one process all found files in a loop:

```<code> foreach(var sourceFile in Directory.EnumerateFiles(sourceDirectory, "*.xls"))
 {
     var sourceFileName = Path.GetFileName(sourceFile);
     var targetFileName = Path.Combine(targetDirectory, sourceFileName);
     File.Move(sourceFileName, targetFileName);
 }
</code>```

Body:
One of my executable process produces two files. I want to move one file that is produced to shared drive. I am writing an automatic process to move the file from one location to shared drive. The only issue is file name changes every time the executable is run so I don't have the exact filename with me. I only have the extension, .xls. I have only one .xls file in my directory.

I tried doing this

File.Copy(@"*.xls", @"\\serv44\Application\testing\name\test2\*.xls", true);

It threw an error saying Invalid name. After moving the file to shared drive. I want to delete the .xls file.

File.Delete("*.xls");

any help will be appreciated

Body:
You should get file name and then do whatever you want with that file. I.e. if you have only one xls file in the source directory:

var targetDirectory = @"\\serv44\Application\testing\name\test2\";
var sourceFile = Directory.EnumerateFiles(sourceDirectory, "*.xls").FirstOrDefault();
if (sourceFile != null)
{
    var sourceFileName = Path.GetFileName(sourceFile);
    var targetFileName = Path.Combine(targetDirectory, sourceFileName);
    File.Copy(sourceFileName, targetFileName);
    File.Delete(sourceFileName);
}

Note: instead of copy and delete you can use single Move operation.

If you want to move several files from your source directory, then instead of taking first one process all found files in a loop:

 foreach(var sourceFile in Directory.EnumerateFiles(sourceDirectory, "*.xls"))
 {
     var sourceFileName = Path.GetFileName(sourceFile);
     var targetFileName = Path.Combine(targetDirectory, sourceFileName);
     File.Move(sourceFileName, targetFileName);
 }


问:
Event Flow Filters Not Correctly Filtering Using Event Source As Input And ApplicationInsights as Output. Any ideas?
I am using event flow to send telemetry data to application insights in a service fabric application. The events seem to be created correctly but I seem to be encountering problems with the eventFlow filtering. When I try to filter my events as a exception or dependency they do not appear inside the application insights portal on Azure.

My logging events are created using eventSource.

Here is my output section from eventFlowConfig.json:

```<code>"outputs": [
    {
      "type": "ApplicationInsights",
      "instrumentationKey": "****************************************",
      "filters": [
        {
          "type": "metadata",
          "metadata": "exception",
          "include": "EventId == 10",
          "exceptionProperty": "operationType"
        }
      ]
</code>```

Here are the versions of the packages I am using which are most relevant to this problem:

```<code><package id="Microsoft.Diagnostics.EventFlow.Core" version="1.1.4" targetFramework="net46" />
  <package id="Microsoft.Diagnostics.EventFlow.EtwUtilities" version="1.1.0" targetFramework="net46" />
  <package id="Microsoft.Diagnostics.EventFlow.Inputs.EventSource" version="1.1.1" targetFramework="net46" />
  <package id="Microsoft.Diagnostics.EventFlow.Outputs.ApplicationInsights" version="1.1.4" targetFramework="net46" />
  <package id="Microsoft.Diagnostics.EventFlow.ServiceFabric" version="1.1.3" targetFramework="net46" />
  <package id="Microsoft.ApplicationInsights" version="2.4.0-beta4" targetFramework="net46" />
</code>```

答:
Basically, the exception property needs to contain an exception object, otherwise metadata decoration will fail. I do not think "operationType" property carries an exception, does it? See https://github.com/Azure/diagnostics-eventflow/issues/92 for some ideas on how to deal with this.

There is also an issue that if metadata decoration fails, the event just gets dropped by Application Insights output. This is tracked by https://github.com/Azure/diagnostics-eventflow/issues/95 We'll fix this soon.

Body:
I am using event flow to send telemetry data to application insights in a service fabric application. The events seem to be created correctly but I seem to be encountering problems with the eventFlow filtering. When I try to filter my events as a exception or dependency they do not appear inside the application insights portal on Azure.

My logging events are created using eventSource.

Here is my output section from eventFlowConfig.json:

"outputs": [
    {
      "type": "ApplicationInsights",
      "instrumentationKey": "****************************************",
      "filters": [
        {
          "type": "metadata",
          "metadata": "exception",
          "include": "EventId == 10",
          "exceptionProperty": "operationType"
        }
      ]

Here are the versions of the packages I am using which are most relevant to this problem:

<package id="Microsoft.Diagnostics.EventFlow.Core" version="1.1.4" targetFramework="net46" />
  <package id="Microsoft.Diagnostics.EventFlow.EtwUtilities" version="1.1.0" targetFramework="net46" />
  <package id="Microsoft.Diagnostics.EventFlow.Inputs.EventSource" version="1.1.1" targetFramework="net46" />
  <package id="Microsoft.Diagnostics.EventFlow.Outputs.ApplicationInsights" version="1.1.4" targetFramework="net46" />
  <package id="Microsoft.Diagnostics.EventFlow.ServiceFabric" version="1.1.3" targetFramework="net46" />
  <package id="Microsoft.ApplicationInsights" version="2.4.0-beta4" targetFramework="net46" />