问:
Parse right of last found from email body
I have emails with the following type:

I am extracting the NAME and CITY but I want to extract also the problem for each field : NAME Because is WRONG and CITY Because it can't be READ

Until now I can extract one problem overall for each email - the first encounter.

```<code>Sub Problems()
    Dim myOlApp As New Outlook.Application
    Dim myNameSpace As Outlook.NameSpace
    Dim myInbox As Outlook.MAPIFolder
    Dim myitems As Outlook.items
    Dim myitem As Object
    Dim Found As Boolean

    Set myNameSpace = myOlApp.GetNamespace("MAPI")
    Set myInbox = myNameSpace.GetDefaultFolder(olFolderInbox)
    Set myitems = GetFolderPatharchive("aaa\bbb").items
    Found = False

    Dim olkMsg As Object, _
        olkFld As Object, _
        excApp As Object, _
        excWkb As Object, _
        excWks As Object, _
        intRow As Integer, _
        intCnt As Integer, _
        data_email As String, _
        strFilename As String, _
        arrCells As Variant, _
        varb As Variant, varD As Variant, varF As Variant

    strFilename = "C:\OVERVIEW\EXTRACT EMAIL1"
    If strFilename <> vbNullString Then
        Set excApp = CreateObject("Excel.Application")
        Set excWkb = excApp.Workbooks.Add()
        Set excWks = excWkb.ActiveSheet
        excApp.DisplayAlerts = False
        With excWks
            .Cells(1, 1) = "SENDER"
            .Cells(1, 2) = "SUBJECT"
            .Cells(1, 3) = "CITY"
            .Cells(1, 4) = "DATE"
            .Cells(1, 5) = "HOUR"
            .Cells(1, 6) = "FIELD"
            .Cells(1, 7) = "PROBLEM"
        End With

        intRow = 2

        For Each olkMsg In myitems
            If olkMsg.Class <> olMail Then
            Else
                arrCells = Split(GetCells(olkMsg.HTMLBody), Chr(255))
                For intCnt = LBound(arrCells) To UBound(arrCells) Step 1

On Error GoTo Handler
                    varb = arrCells(intCnt)
                    Dim line As Integer
                    line = InStr(olkMsg.Subject, "-")

                    excWks.Cells(intRow, 1) = olkMsg.SenderName
                    excWks.Cells(intRow, 2) = Left(olkMsg.Subject, line - 1)
                    excWks.Cells(intRow, 3) = Left(olkMsg.Subject, 4)
                    excWks.Cells(intRow, 4) = Format(olkMsg.ReceivedTime, "dd.mm.yyyy")
                    excWks.Cells(intRow, 5) = Format(olkMsg.ReceivedTime, "Hh:Nn:Ss")
                    excWks.Cells(intRow, 6) = varb

                    Dim strAddr As String
                    strAddr = ParseTextLinePair(olkMsg.Body, "WRONG")
                    If strAddr <> vbNullString Then excWks.Cells(intRow, 7) = "WRONG"

                    intRow = intRow + 1
                Next intCnt
            End If
Label1:
        Next olkMsg

        Set olkMsg = Nothing
        excWkb.SaveAs strFilename, 52
        excWkb.Close
    End If

    Set olkFld = Nothing
    Set excWks = Nothing
    Set excWkb = Nothing
    Set excApp = Nothing

    MsgBox "TA DAM! EMAILS EXPORTED", vbInformation + vbOKOnly
    Call opexlN
Exit Sub
Handler:
    Resume Label1
End Sub

Function ParseTextLinePair _
  (strSource As String, strLabel As String)
    Dim intLocLabel As Integer
    Dim intLocCRLF As Integer
    Dim intLenLabel As Integer
    Dim strText As String
    intLocLabel = InStr(strSource, strLabel)
    intLenLabel = Len(strLabel)
        If intLocLabel > 0 Then
        intLocCRLF = InStr(intLocLabel, strSource, vbCrLf)
        If intLocCRLF > 0 Then
            intLocLabel = intLocLabel + intLenLabel
            strText = Mid(strSource, _
                            intLocLabel, _
                            intLocCRLF - intLocLabel)
        Else
            intLocLabel = _
              Mid(strSource, intLocLabel + intLenLabel)
        End If
    End If
    ParseTextLinePair = Trim(strText)
End Function

Function GetFolderPatharchive(ByVal FolderPath As String) As Outlook.Folder
    Dim oFolder As Outlook.Folder
    Dim FoldersArray As Variant
    Dim i As Integer

    On Error GoTo GetFolderPatharchive_Error
    If Left(FolderPath, 2) = "\\" Then
        FolderPath = Right(FolderPath, Len(FolderPath) - 2)
    End If
    'Convert folderpath to array
    FoldersArray = Split(FolderPath, "\")
    Set oFolder = Application.Session.Folders.Item(FoldersArray(0))
    If Not oFolder Is Nothing Then
        For i = 1 To UBound(FoldersArray, 1)
            Dim SubFolders As Outlook.Folders
            Set SubFolders = oFolder.Folders
            Set oFolder = SubFolders.Item(FoldersArray(i))
            If oFolder Is Nothing Then
                Set GetFolderPatharchive = Nothing
            End If
        Next
    End If
    'Return the oFolder
    Set GetFolderPatharchive = oFolder
    Exit Function

GetFolderPatharchive_Error:
    Set GetFolderPatharchive = Nothing
    Exit Function
End Function

Private Function GetCells(strHTML As String) As String
    Const READYSTATE_COMPLETE = 4
    Dim objIE As Object, objDoc As Object, colCells As Object, objCell As Object
    Set objIE = CreateObject("InternetExplorer.Application")
    objIE.Navigate "about:blank"
    Do Until objIE.ReadyState = READYSTATE_COMPLETE
    DoEvents
    Loop
    objIE.Document.body.innerHTML = strHTML
    Set objDoc = objIE.Document
    Set colCells = objDoc.getElementsByTagName("td")
    If colCells.Length > 0 Then
        For Each objCell In colCells
            GetCells = GetCells & objCell.innerText & Chr(255)
        Next
        GetCells = Left(GetCells, Len(GetCells) - 1)
    Else
        GetCells = ""
    End If
Set objCell = Nothing
Set colCells = Nothing
Set objDoc = Nothing
objIE.Quit
Set objIE = Nothing
End Function
</code>```

答:
I would do it like this :

```<code>Sub Problems()
    Dim myOlApp As New Outlook.Application
    Dim myNameSpace As Outlook.NameSpace
    Dim myInbox As Outlook.MAPIFolder
    Dim myitems As Outlook.items
    Dim myitem As Object
    Dim Found As Boolean

    Set myNameSpace = myOlApp.GetNamespace("MAPI")
    Set myInbox = myNameSpace.GetDefaultFolder(olFolderInbox)
    Set myitems = GetFolderPatharchive("aaa\bbb").items
    Found = False

    Dim olkMsg As Object, _
        olkFld As Object, _
        excApp As Object, _
        excWkb As Object, _
        excWks As Object, _
        intRow As Integer, _
        intCnt As Integer, _
        data_email As String, _
        strFilename As String, _
        arrCells As Variant, _
        varB As Variant, varD As Variant, varF As Variant

    strFilename = "C:\OVERVIEW\EXTRACT EMAIL1"
    If strFilename <> vbNullString Then
        Set excApp = CreateObject("Excel.Application")
        Set excWkb = excApp.Workbooks.Add()
        Set excWks = excWkb.ActiveSheet
        excApp.DisplayAlerts = False
        With excWks
            .Cells(1, 1) = "SENDER"
            .Cells(1, 2) = "SUBJECT"
            .Cells(1, 3) = "CITY"
            .Cells(1, 4) = "DATE"
            .Cells(1, 5) = "HOUR"
            .Cells(1, 6) = "FIELD"
            .Cells(1, 7) = "PROBLEM"
        End With 'excWks

        intRow = 2

        For Each olkMsg In myitems
            If olkMsg.Class <> olMail Then
            Else
                arrCells = Split(GetCells(olkMsg.HTMLBody), Chr(255))
                For intCnt = LBound(arrCells) To UBound(arrCells) Step 1

On Error GoTo Handler
                    varB = arrCells(intCnt)
                    Dim LgLocCell As Long
                    LgLocCell = InStr(1, olkMsg.Body, varB)
                    Dim LgLocReason As Long
                    LgLocReason = InStr(LgLocCell + Len(varB), olkMsg.Body, "because", vbTextCompare) + 6

                    Dim line As Integer
                    line = InStr(olkMsg.Subject, "-")
                    With excWks
                        .Cells(intRow, 1) = olkMsg.SenderName
                        .Cells(intRow, 2) = Left(olkMsg.Subject, line - 1)
                        .Cells(intRow, 3) = Left(olkMsg.Subject, 4)
                        .Cells(intRow, 4) = Format(olkMsg.ReceivedTime, "dd.mm.yyyy")
                        .Cells(intRow, 5) = Format(olkMsg.ReceivedTime, "Hh:Nn:Ss")
                        .Cells(intRow, 6) = varB
                        .Cells(intRow, 7) = Trim(Mid(olkMsg.Body, LgLocReason, InStr(LgLocReason + 1, olkMsg.Body, ".") - LgLocReason))
                    End With 'excWks
                    intRow = intRow + 1
                Next intCnt
            End If
Label1:
        Next olkMsg

        Set olkMsg = Nothing
        excWkb.SaveAs strFilename, 52
        excWkb.Close
    End If

    Set olkFld = Nothing
    Set excWks = Nothing
    Set excWkb = Nothing
    Set excApp = Nothing

    MsgBox "TA DAM! EMAILS EXPORTED", vbInformation + vbOKOnly
    Call opexlN
Exit Sub
Handler:
    Resume Label1
End Sub
</code>```

Your function wasn't right, in case you didn't find vbCrLf you were putting a string inside the integer intLocLabel which would cause a Type Mismatch error!

I'm not sure what you want to do when you don't find the line return, because your Mid() in that case is only returning 1 character after the text you were looking for!

I set it to return an empty string! ;)

```<code>Function ParseTextLinePair _
  (strSource As String, strLabel As String)
    Dim intLocLabel As Integer
    Dim intLocCRLF As Integer
    Dim intLenLabel As Integer
    Dim strText As String
    intLocLabel = InStr(strSource, strLabel)
    intLenLabel = Len(strLabel)
        If intLocLabel > 0 Then
        intLocCRLF = InStr(intLocLabel, strSource, vbCrLf)
        If intLocCRLF > 0 Then
            intLocLabel = intLocLabel + intLenLabel
            strText = Mid(strSource, _
                            intLocLabel, _
                            intLocCRLF - intLocLabel)
        Else
            'strText = _
              Mid(strSource, intLocLabel + intLenLabel)
            strText = vbNullString
        End If
    End If
    ParseTextLinePair = Trim(strText)
End Function
</code>```

Body:
I have emails with the following type:

I am extracting the NAME and CITY but I want to extract also the problem for each field : NAME Because is WRONG and CITY Because it can't be READ

Until now I can extract one problem overall for each email - the first encounter.

Sub Problems()
    Dim myOlApp As New Outlook.Application
    Dim myNameSpace As Outlook.NameSpace
    Dim myInbox As Outlook.MAPIFolder
    Dim myitems As Outlook.items
    Dim myitem As Object
    Dim Found As Boolean

    Set myNameSpace = myOlApp.GetNamespace("MAPI")
    Set myInbox = myNameSpace.GetDefaultFolder(olFolderInbox)
    Set myitems = GetFolderPatharchive("aaa\bbb").items
    Found = False

    Dim olkMsg As Object, _
        olkFld As Object, _
        excApp As Object, _
        excWkb As Object, _
        excWks As Object, _
        intRow As Integer, _
        intCnt As Integer, _
        data_email As String, _
        strFilename As String, _
        arrCells As Variant, _
        varb As Variant, varD As Variant, varF As Variant

    strFilename = "C:\OVERVIEW\EXTRACT EMAIL1"
    If strFilename <> vbNullString Then
        Set excApp = CreateObject("Excel.Application")
        Set excWkb = excApp.Workbooks.Add()
        Set excWks = excWkb.ActiveSheet
        excApp.DisplayAlerts = False
        With excWks
            .Cells(1, 1) = "SENDER"
            .Cells(1, 2) = "SUBJECT"
            .Cells(1, 3) = "CITY"
            .Cells(1, 4) = "DATE"
            .Cells(1, 5) = "HOUR"
            .Cells(1, 6) = "FIELD"
            .Cells(1, 7) = "PROBLEM"
        End With

        intRow = 2

        For Each olkMsg In myitems
            If olkMsg.Class <> olMail Then
            Else
                arrCells = Split(GetCells(olkMsg.HTMLBody), Chr(255))
                For intCnt = LBound(arrCells) To UBound(arrCells) Step 1

On Error GoTo Handler
                    varb = arrCells(intCnt)
                    Dim line As Integer
                    line = InStr(olkMsg.Subject, "-")

                    excWks.Cells(intRow, 1) = olkMsg.SenderName
                    excWks.Cells(intRow, 2) = Left(olkMsg.Subject, line - 1)
                    excWks.Cells(intRow, 3) = Left(olkMsg.Subject, 4)
                    excWks.Cells(intRow, 4) = Format(olkMsg.ReceivedTime, "dd.mm.yyyy")
                    excWks.Cells(intRow, 5) = Format(olkMsg.ReceivedTime, "Hh:Nn:Ss")
                    excWks.Cells(intRow, 6) = varb

                    Dim strAddr As String
                    strAddr = ParseTextLinePair(olkMsg.Body, "WRONG")
                    If strAddr <> vbNullString Then excWks.Cells(intRow, 7) = "WRONG"

                    intRow = intRow + 1
                Next intCnt
            End If
Label1:
        Next olkMsg

        Set olkMsg = Nothing
        excWkb.SaveAs strFilename, 52
        excWkb.Close
    End If

    Set olkFld = Nothing
    Set excWks = Nothing
    Set excWkb = Nothing
    Set excApp = Nothing

    MsgBox "TA DAM! EMAILS EXPORTED", vbInformation + vbOKOnly
    Call opexlN
Exit Sub
Handler:
    Resume Label1
End Sub

Function ParseTextLinePair _
  (strSource As String, strLabel As String)
    Dim intLocLabel As Integer
    Dim intLocCRLF As Integer
    Dim intLenLabel As Integer
    Dim strText As String
    intLocLabel = InStr(strSource, strLabel)
    intLenLabel = Len(strLabel)
        If intLocLabel > 0 Then
        intLocCRLF = InStr(intLocLabel, strSource, vbCrLf)
        If intLocCRLF > 0 Then
            intLocLabel = intLocLabel + intLenLabel
            strText = Mid(strSource, _
                            intLocLabel, _
                            intLocCRLF - intLocLabel)
        Else
            intLocLabel = _
              Mid(strSource, intLocLabel + intLenLabel)
        End If
    End If
    ParseTextLinePair = Trim(strText)
End Function

Function GetFolderPatharchive(ByVal FolderPath As String) As Outlook.Folder
    Dim oFolder As Outlook.Folder
    Dim FoldersArray As Variant
    Dim i As Integer

    On Error GoTo GetFolderPatharchive_Error
    If Left(FolderPath, 2) = "\\" Then
        FolderPath = Right(FolderPath, Len(FolderPath) - 2)
    End If
    'Convert folderpath to array
    FoldersArray = Split(FolderPath, "\")
    Set oFolder = Application.Session.Folders.Item(FoldersArray(0))
    If Not oFolder Is Nothing Then
        For i = 1 To UBound(FoldersArray, 1)
            Dim SubFolders As Outlook.Folders
            Set SubFolders = oFolder.Folders
            Set oFolder = SubFolders.Item(FoldersArray(i))
            If oFolder Is Nothing Then
                Set GetFolderPatharchive = Nothing
            End If
        Next
    End If
    'Return the oFolder
    Set GetFolderPatharchive = oFolder
    Exit Function

GetFolderPatharchive_Error:
    Set GetFolderPatharchive = Nothing
    Exit Function
End Function

Private Function GetCells(strHTML As String) As String
    Const READYSTATE_COMPLETE = 4
    Dim objIE As Object, objDoc As Object, colCells As Object, objCell As Object
    Set objIE = CreateObject("InternetExplorer.Application")
    objIE.Navigate "about:blank"
    Do Until objIE.ReadyState = READYSTATE_COMPLETE
    DoEvents
    Loop
    objIE.Document.body.innerHTML = strHTML
    Set objDoc = objIE.Document
    Set colCells = objDoc.getElementsByTagName("td")
    If colCells.Length > 0 Then
        For Each objCell In colCells
            GetCells = GetCells & objCell.innerText & Chr(255)
        Next
        GetCells = Left(GetCells, Len(GetCells) - 1)
    Else
        GetCells = ""
    End If
Set objCell = Nothing
Set colCells = Nothing
Set objDoc = Nothing
objIE.Quit
Set objIE = Nothing
End Function

Body:
I would do it like this :

Sub Problems()
    Dim myOlApp As New Outlook.Application
    Dim myNameSpace As Outlook.NameSpace
    Dim myInbox As Outlook.MAPIFolder
    Dim myitems As Outlook.items
    Dim myitem As Object
    Dim Found As Boolean

    Set myNameSpace = myOlApp.GetNamespace("MAPI")
    Set myInbox = myNameSpace.GetDefaultFolder(olFolderInbox)
    Set myitems = GetFolderPatharchive("aaa\bbb").items
    Found = False

    Dim olkMsg As Object, _
        olkFld As Object, _
        excApp As Object, _
        excWkb As Object, _
        excWks As Object, _
        intRow As Integer, _
        intCnt As Integer, _
        data_email As String, _
        strFilename As String, _
        arrCells As Variant, _
        varB As Variant, varD As Variant, varF As Variant

    strFilename = "C:\OVERVIEW\EXTRACT EMAIL1"
    If strFilename <> vbNullString Then
        Set excApp = CreateObject("Excel.Application")
        Set excWkb = excApp.Workbooks.Add()
        Set excWks = excWkb.ActiveSheet
        excApp.DisplayAlerts = False
        With excWks
            .Cells(1, 1) = "SENDER"
            .Cells(1, 2) = "SUBJECT"
            .Cells(1, 3) = "CITY"
            .Cells(1, 4) = "DATE"
            .Cells(1, 5) = "HOUR"
            .Cells(1, 6) = "FIELD"
            .Cells(1, 7) = "PROBLEM"
        End With 'excWks

        intRow = 2

        For Each olkMsg In myitems
            If olkMsg.Class <> olMail Then
            Else
                arrCells = Split(GetCells(olkMsg.HTMLBody), Chr(255))
                For intCnt = LBound(arrCells) To UBound(arrCells) Step 1

On Error GoTo Handler
                    varB = arrCells(intCnt)
                    Dim LgLocCell As Long
                    LgLocCell = InStr(1, olkMsg.Body, varB)
                    Dim LgLocReason As Long
                    LgLocReason = InStr(LgLocCell + Len(varB), olkMsg.Body, "because", vbTextCompare) + 6

                    Dim line As Integer
                    line = InStr(olkMsg.Subject, "-")
                    With excWks
                        .Cells(intRow, 1) = olkMsg.SenderName
                        .Cells(intRow, 2) = Left(olkMsg.Subject, line - 1)
                        .Cells(intRow, 3) = Left(olkMsg.Subject, 4)
                        .Cells(intRow, 4) = Format(olkMsg.ReceivedTime, "dd.mm.yyyy")
                        .Cells(intRow, 5) = Format(olkMsg.ReceivedTime, "Hh:Nn:Ss")
                        .Cells(intRow, 6) = varB
                        .Cells(intRow, 7) = Trim(Mid(olkMsg.Body, LgLocReason, InStr(LgLocReason + 1, olkMsg.Body, ".") - LgLocReason))
                    End With 'excWks
                    intRow = intRow + 1
                Next intCnt
            End If
Label1:
        Next olkMsg

        Set olkMsg = Nothing
        excWkb.SaveAs strFilename, 52
        excWkb.Close
    End If

    Set olkFld = Nothing
    Set excWks = Nothing
    Set excWkb = Nothing
    Set excApp = Nothing

    MsgBox "TA DAM! EMAILS EXPORTED", vbInformation + vbOKOnly
    Call opexlN
Exit Sub
Handler:
    Resume Label1
End Sub

Your function wasn't right, in case you didn't find vbCrLf you were putting a string inside the integer intLocLabel which would cause a Type Mismatch error!

I'm not sure what you want to do when you don't find the line return, because your Mid() in that case is only returning 1 character after the text you were looking for!

I set it to return an empty string! ;)

Function ParseTextLinePair _
  (strSource As String, strLabel As String)
    Dim intLocLabel As Integer
    Dim intLocCRLF As Integer
    Dim intLenLabel As Integer
    Dim strText As String
    intLocLabel = InStr(strSource, strLabel)
    intLenLabel = Len(strLabel)
        If intLocLabel > 0 Then
        intLocCRLF = InStr(intLocLabel, strSource, vbCrLf)
        If intLocCRLF > 0 Then
            intLocLabel = intLocLabel + intLenLabel
            strText = Mid(strSource, _
                            intLocLabel, _
                            intLocCRLF - intLocLabel)
        Else
            'strText = _
              Mid(strSource, intLocLabel + intLenLabel)
            strText = vbNullString
        End If
    End If
    ParseTextLinePair = Trim(strText)
End Function


来源: stackexchange

问:
Reversing array elements in C programming
I am new to C and I have a problem. I need to reverse the elements of arrays in the following program. Can I get a very simple explanation of what I am doing wrong and how I could go on about fixing it?

Here's the output I get:

```Enter number 0: 0
Enter number 1: 1
Enter number 2: 2
Enter number 3: 3
Enter number 4: 4
Enter number 5: 5
Enter number 6: 6
Enter number 7: 7
Element 0 is: 7
Element 1 is: 6
Element 2 is: 5
Element 3 is: 4
Element 4 is: 4
Element 5 is: 5
Element 6 is: 6
Element 7 is: 7
```

My code:

```<code>#include <stdio.h>

void reverse(int a[], int i)
{
    int j=7,b;
    for (i=0; i<=7; i++)
    {
        b=a[i];
        a[i]=a[j];
        a[j]=b;
        printf("Element %d is: %d\n", i,a[i]);
        j--;
    }
}

int main(void)
{
    int a[8];
    int i;
    for(i=0;i<=7;i++)
    {
        printf("Enter number %d: ",i);
        scanf("%d", &a[i]);
    }
    reverse(a, 8);
    return 0;
}
</code>```

答:
```<code>The Principe is simple. just stand at the middle of the table and reverse the elements as follow. so pose n is lent of the table. then the last element is n-1.

so you ave to reverse position t[0] and t[n-2]
reverse t[1] and t[n-3] and so on...

stop when you rich the middle of the table. try to code your self is better than for me giving you the code.
hope it helped.
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I am new to C and I have a problem. I need to reverse the elements of arrays in the following program. Can I get a very simple explanation of what I am doing wrong and how I could go on about fixing it?

Here's the output I get:

Enter number 0: 0
Enter number 1: 1
Enter number 2: 2
Enter number 3: 3
Enter number 4: 4
Enter number 5: 5
Enter number 6: 6
Enter number 7: 7
Element 0 is: 7
Element 1 is: 6
Element 2 is: 5
Element 3 is: 4
Element 4 is: 4
Element 5 is: 5
Element 6 is: 6
Element 7 is: 7

My code:

#include <stdio.h>

void reverse(int a[], int i)
{
    int j=7,b;
    for (i=0; i<=7; i++)
    {
        b=a[i];
        a[i]=a[j];
        a[j]=b;
        printf("Element %d is: %d\n", i,a[i]);
        j--;
    }
}

int main(void)
{
    int a[8];
    int i;
    for(i=0;i<=7;i++)
    {
        printf("Enter number %d: ",i);
        scanf("%d", &a[i]);
    }
    reverse(a, 8);
    return 0;
}


问:
VS 2017 - Very slow (laggy) when debugging
When I debug my solution, vs 2017 is very laggy and slow it's like it has to operate something heavy in the background.

So it stops "responding" every 5 seconds for 2 seconds, which is very annoying.
Any suggestions?

EDIT (tried suggestions):

Browser Link is turned off

Stopped customer feedback

答:
If disable Diagnostic Tools don't fix the problem try to disable IntelliTrace,
Unchecking Enable IntelliTrace, in  Tools -> Options -> IntelliTrace.
Work for me.</p>


问:
How to scale video to be as large as possible so that the background area is completely covered by the background video
I want to create a background video using HTML5 so it will scale as large as possible so that the background area is completely covered by the background video, something similarly to the background-size: cover;, but to the video.

I want it to be as cross-platform/browser as possible.

EDIT

I meant background-size: cover;

Sorry for that :/

答:
you can try using

```<code>background-size: 100vw 100vh;
</code>```

vw- view width of the screen

  vh-view height of the screen

read this

Body:
you can try using

background-size: 100vw 100vh;

vw- view width of the screen

  vh-view height of the screen

read this


问:
After deploying django in AWS EB its not working similarly as it runs in localhost
This is how Admin page works in local host

This is how its showing after deploying in AWS EB

can i get help on this like how to get it normal or how to modify it using my own templates please .

答:
Before deploying run : python manage.py collectstatic

After running this you should deploy again like you usually do.


问:
Install Umbraco on Git
I have a question about Umbraco and Git. We have to work on Umbraco with 2 persons and we would like to use Git. I use GitHub for Windows to push my files to our github repository.

We just copy the umbraco folder to our repository? Or do we have to delete DLL's or .... ?
Does someone has a tutorial about Umbraco and Git?

Thanks in advance!
Niels

答:
If you're using a correct .gitignore file, there is no need to delete files when committing your code.

Based on your use case, you could use the VisualStudio and Umbraco files from the GitHub gitignore collection. Just combine both files (in respective order) as .gitignore file in the root of your repository.

Also, I would use the NuGet setup method, so upgrading should be a simple package update (see instructions). And don't forget the version specific upgrade instructions.

Title: Install Umbraco on Git


问:
How to provide a button which will change my current page content to an previous page in drupal
I'm making a site wherein I want to show the current course that I'm gonna teach to my pupils.In this page there should also be links provided to my previous courses. Now when I'm done with this course I want to transfer it to a previous course or rather automatically create a link for it and get the new course content in it's place. I just think doing manually is kind of stupid. Rather I want to have a form where i can create my new course then click on make current course as previous and this course as new whenever i wish.How can I do this.Is this even possible</p>

答:
Easy man. Just create a content type called "course" and using CCK, add all the fields to capture information you want about the course.

Now you have the content. Using Views, create a simple view page displaying course content type and sort it on descending order, set it to display one item at a time and add a mini pager. That way the new course will be the first one displayed and the other ones will be behind it. You might need to customize the pager a bit ^^

ContentLicense: CC BY-SA 2.5


问:
Custom code snippet for WebStorm and PhpStorm
I use custom code snippet for Sublime Text like custom comments, function, reusable block code, CDN and more.. but I could not do that in WebStorm and PhpStorm IDE.

Here is my building block code snippet (comments) for Sublime Text:

```<code> /*============================
            comments
   ============================*/
</code>```

and this code blocks for HTML5 comments

```<code> <!-----------------------
           comments
   ----------------------->
</code>```

Moreover I'm new user for JetBrains software. Can I use custom code snippet above in JetBrains software ?

答:
It's called Live Templates in JetBrains IDEs.

Available at Settings/Preferences | Editor | Live Templates.

You can use existing Live Templates as is, alter them to your needs or create your own.

Creating own is better be done in own group -- they will be stored in separate config file so easier to share, no possible conflicts with built-in ones (easier to update between versions etc.). It also makes perfect sense to use separate group per language -- the same abbreviation can be used for different languages/context but abbreviation within the same group must be unique.

BTW -- I'd say -- do not edit built-ins at all -- just disable specific built-in template and create your own version of it in separate group. This way you can always see what fix/change devs have made in new IDE version etc.

Full official tutorial/how-to is available here: https://confluence.jetbrains.com/display/PhpStorm/Live+Templates+%28Snippets%29+in+PhpStorm

You may also be interested in other articles:

https://confluence.jetbrains.com/display/PhpStorm/Tutorials

in particular (since you have used Sublime in the past): https://confluence.jetbrains.com/display/PhpStorm/PhpStorm+for+Users+of+Text+Editors

Body:
I use custom code snippet for Sublime Text like custom comments, function, reusable block code, CDN and more.. but I could not do that in WebStorm and PhpStorm IDE.

Here is my building block code snippet (comments) for Sublime Text:

 /*============================
            comments
   ============================*/

and this code blocks for HTML5 comments

Moreover I'm new user for JetBrains software. Can I use custom code snippet above in JetBrains software ?


问:
Contenteditable div is not working
contenteditable is not working properly,if we write the text in between of the sentence.cursor position goes to the end of the sentence.

var changed,
    lastValue = '',
    div = $('#ce'),
    words = ['oele', 'geel', 'politie', 'foo bar'];

function markWords() {
    var html = div.html().replace(/<\/?strong>/gi, ''),
        text = html.replace(/<[^>]+>/g, ' ').replace(/\s+/g, ' '),
        exp;
    $.each(words, function(i, word) {
        exp = new RegExp('\\b(' + word + ')\\b', 'gi');
        html = html.replace(exp, function(m) {
console.log('WORD MATCH:', m);
            return '' + m + '';
        });
    });
    //html = html.replace(' ', ' ').replace(/\s+/g, ' ');
console.log('HTML:', html);
console.log('----');
    div.html(html);
}

setInterval(function() {
    var html = div.html();
    if ( lastValue != html && html ) {
//console.log(lastValue);
//console.log(html);
//console.log('----');
        lastValue = html;
        markWords();
        setEndOfContenteditable(div[0]);
    }
}, 500);

function setEndOfContenteditable(contentEditableElement)
{
    var range,selection;
    if(document.createRange)//Firefox, Chrome, Opera, Safari, IE 9+
    {
        range = document.createRange();//Create a range (a range is a like the selection but invisible)
        range.selectNodeContents(contentEditableElement);//Select the entire contents of the element with the range
        range.collapse(false);//collapse the range to the end point. false means collapse to end rather than the start
        selection = window.getSelection();//get the selection object (allows you to change selection)
        selection.removeAllRanges();//remove any selections already made
        selection.addRange(range);//make the range you have just created the visible selection
    }
    else if(document.selection)//IE 8 and lower
    {
        range = document.body.createTextRange();//Create a range (a range is a like the selection but invisible)
        range.moveToElementText(contentEditableElement);//Select the entire contents of the element with the range
        range.collapse(false);//collapse the range to the end point. false means collapse to end rather than the start
        range.select();//Select the range (make it the visible selection
    }
}```
<pre class="snippet-code-css lang-css prettyprint-override"><code>[contenteditable] {
    padding: 10px;
    border: dotted 1px #aaa;
}
[contenteditable] > div {
    margin: 10px 0;
}
[contenteditable] strong {
    font-weight: normal;
    background: red;
    color: white;
}</code>```

I love me some foo bar and shit.

clear
```

答:
Edited parts

Use range.setStart and range.setEndto set the position

Change the callback function in the setInterval to a seperate function.

Instead of setInterval, use setTimeout to invoke the function at only one time and then from the setEndOfContenteditable, invoke the function.

var changed,
    lastValue = '',
    div = $('#ce'),
    words = ['oele', 'geel', 'politie', 'foo bar'];

function markWords() {
    var html = div.html().replace(/<\/?strong>/gi, ''),
        text = html.replace(/<[^>]+>/g, ' ').replace(/\s+/g, ' '),
        exp;
    $.each(words, function(i, word) {
        exp = new RegExp('\\b(' + word + ')\\b', 'gi');
        html = html.replace(exp, function(m) {
            return '' + m + '';
        });
    });
    setPos();
    div.html(html);
    setEndOfContenteditable(div[0]);
    console.log(pos);
}
function start() {
    var html = div.html();
    if ( lastValue != html && html ) {
        lastValue = html;
        setPos();
        markWords();
        setEndOfContenteditable(div[0]);
    }
}
setTimeout(start, 1000);
var pos=0;
function setPos(){
  if($(window.getSelection().anchorNode).is($(this))){
      pos=0;
  }else{
      pos=window.getSelection().anchorOffset;
 }
}
$("#ce").on('keyup',function(e){
       start();
    });
function setEndOfContenteditable(contentEditableElement)
{
    var range,selection;

    if(document.createRange)
    {
        range = document.createRange();
        range.selectNodeContents(contentEditableElement);
        range.setStart(contentEditableElement.firstChild, pos);
        range.setEnd(contentEditableElement.firstChild, pos);
        //range.collapse();
        selection = window.getSelection();
        selection.removeAllRanges();
        selection.addRange(range);
    }
    start();
}```
<pre class="snippet-code-css lang-css prettyprint-override"><code>[contenteditable] {
    padding: 10px;
    border: dotted 1px #aaa;
}
[contenteditable] > div {
    margin: 10px 0;
}
[contenteditable] strong {
    font-weight: normal;
    background: red;
    color: white;
}</code>```

I love me some foo bar and shit.

clear
```

Title: Contenteditable div is not working

Body:
contenteditable is not working properly,if we write the text in between of the sentence.cursor position goes to the end of the sentence.

var changed,
    lastValue = '',
    div = $('#ce'),
    words = ['oele', 'geel', 'politie', 'foo bar'];

function markWords() {
    var html = div.html().replace(/<\/?strong>/gi, ''),
        text = html.replace(/<[^>]+>/g, ' ').replace(/\s+/g, ' '),
        exp;
    $.each(words, function(i, word) {
        exp = new RegExp('\\b(' + word + ')\\b', 'gi');
        html = html.replace(exp, function(m) {
console.log('WORD MATCH:', m);
            return '' + m + '';
        });
    });
    //html = html.replace(' ', ' ').replace(/\s+/g, ' ');
console.log('HTML:', html);
console.log('----');
    div.html(html);
}

setInterval(function() {
    var html = div.html();
    if ( lastValue != html && html ) {
//console.log(lastValue);
//console.log(html);
//console.log('----');
        lastValue = html;
        markWords();
        setEndOfContenteditable(div[0]);
    }
}, 500);

function setEndOfContenteditable(contentEditableElement)
{
    var range,selection;
    if(document.createRange)//Firefox, Chrome, Opera, Safari, IE 9+
    {
        range = document.createRange();//Create a range (a range is a like the selection but invisible)
        range.selectNodeContents(contentEditableElement);//Select the entire contents of the element with the range
        range.collapse(false);//collapse the range to the end point. false means collapse to end rather than the start
        selection = window.getSelection();//get the selection object (allows you to change selection)
        selection.removeAllRanges();//remove any selections already made
        selection.addRange(range);//make the range you have just created the visible selection
    }
    else if(document.selection)//IE 8 and lower
    {
        range = document.body.createTextRange();//Create a range (a range is a like the selection but invisible)
        range.moveToElementText(contentEditableElement);//Select the entire contents of the element with the range
        range.collapse(false);//collapse the range to the end point. false means collapse to end rather than the start
        range.select();//Select the range (make it the visible selection
    }
}

[contenteditable] {
    padding: 10px;
    border: dotted 1px #aaa;
}
[contenteditable] > div {
    margin: 10px 0;
}
[contenteditable] strong {
    font-weight: normal;
    background: red;
    color: white;
}

I love me some foo bar and shit.

clear

Body:
Edited parts

Use range.setStart and range.setEndto set the position

Change the callback function in the setInterval to a seperate function.

Instead of setInterval, use setTimeout to invoke the function at only one time and then from the setEndOfContenteditable, invoke the function.

var changed,
    lastValue = '',
    div = $('#ce'),
    words = ['oele', 'geel', 'politie', 'foo bar'];

function markWords() {
    var html = div.html().replace(/<\/?strong>/gi, ''),
        text = html.replace(/<[^>]+>/g, ' ').replace(/\s+/g, ' '),
        exp;
    $.each(words, function(i, word) {
        exp = new RegExp('\\b(' + word + ')\\b', 'gi');
        html = html.replace(exp, function(m) {
            return '<strong>' + m + '</strong>';
        });
    });
    setPos();
    div.html(html);
    setEndOfContenteditable(div[0]);
    console.log(pos);
}
function start() {
    var html = div.html();
    if ( lastValue != html && html ) {
        lastValue = html;
        setPos();
        markWords();
        setEndOfContenteditable(div[0]);
    }
}
setTimeout(start, 1000);
var pos=0;
function setPos(){
  if($(window.getSelection().anchorNode).is($(this))){
      pos=0;
  }else{
      pos=window.getSelection().anchorOffset;
 }
}
$("#ce").on('keyup',function(e){
       start();
    });
function setEndOfContenteditable(contentEditableElement)
{
    var range,selection;

    if(document.createRange)
    {
        range = document.createRange();
        range.selectNodeContents(contentEditableElement);
        range.setStart(contentEditableElement.firstChild, pos);
        range.setEnd(contentEditableElement.firstChild, pos);
        //range.collapse();
        selection = window.getSelection();
        selection.removeAllRanges();
        selection.addRange(range);
    }
    start();
}

[contenteditable] {
    padding: 10px;
    border: dotted 1px #aaa;
}
[contenteditable] > div {
    margin: 10px 0;
}
[contenteditable] strong {
    font-weight: normal;
    background: red;
    color: white;
}

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="ce" contenteditable>I love me some foo bar and shit.</div>

<p><a href="javascript:void(0);" onclick="$('#ce').html('');">clear</a></p>


问:
Python find succesive numbers in array/list
I have an array like this arr = [1,2,3,10,11,15] from which I want to have the numbers left and right of each block of successive numbers, i.e. [0,4,9,12,14,16].

答: So you'd want to go over the array in a loop which checks if the number at index[i] is greater than that at index[i+1] and stores it in an array/prints it to console/ect. if that check is true (or false, depending on how you want to do that.)</p>


问:
Java - Flatten nested map using Stream
I have been messing around with Java 8 Stream API and ran into something I could only do through traditional for-loops.

Given a nested map of

```<code>{
    1999: {
             3: [23, 24, 25],
             4: [1, 2, 3]
          },
    2001: {
             11: [12, 13, 14],
             12: [25, 26, 27]

          }
}
</code>```

How can I transform this into

```<code>['23,3,1999', '24,3,1999', '25,3,1999', '1,4,1999', '2,4,1999', '3,4,1999', '12,11,2001', '13,11,2001', '14,11,2001', '25,12,2001', '26,12,2001', '27,12,2001']
</code>```

Basically I want to replicate:

```<code>    Map<Integer, Map<Integer, List<Integer>>> dates...
    List<String> flattened = new ArrayList<>();
    for (Integer key1 : map.keySet()) {
        for (Integer key2 : map.get(key1).keySet()) {
            for (Integer value : map.get(key1).get(key2)) {
                flattened.add(value + "," + key2 + "," + key1);
            }
        }
    }
</code>```

答:
```<code> items
            .entrySet()
            .stream()
            .flatMap(
                    l-> l.getValue().entrySet().stream()
                            .flatMap(
                                    ll->ll.getValue().stream()
                                         .map(lll+","+ll.getKey()+","+l.getKey())))
            .collect(Collectors.toList())
            .forEach(System.out::println);
</code>```

Title: Java - Flatten nested map using Stream

Body:
I have been messing around with Java 8 Stream API and ran into something I could only do through traditional for-loops.

Given a nested map of

{
    1999: {
             3: [23, 24, 25],
             4: [1, 2, 3]
          },
    2001: {
             11: [12, 13, 14],
             12: [25, 26, 27]

          }
}

How can I transform this into

['23,3,1999', '24,3,1999', '25,3,1999', '1,4,1999', '2,4,1999', '3,4,1999', '12,11,2001', '13,11,2001', '14,11,2001', '25,12,2001', '26,12,2001', '27,12,2001']

Basically I want to replicate:

    Map<Integer, Map<Integer, List<Integer>>> dates...
    List<String> flattened = new ArrayList<>();
    for (Integer key1 : map.keySet()) {
        for (Integer key2 : map.get(key1).keySet()) {
            for (Integer value : map.get(key1).get(key2)) {
                flattened.add(value + "," + key2 + "," + key1);
            }
        }
    }


问:
How to put an image over the content of a div?
I want to display my locker image at the right of the div but kept the div size and format.

that's the default state:

that's what happens now when I lock:

And I want to do something like this:

To make this I made this css:

```<code>.imgCadenas{
  width:  100px;
  height: 100px;
  background: url('/cadenas.png');
  text-align: right;
  background-repeat: no-repeat;
  background-size: 100%;
}
</code>```

and the HTML is not special but I put it:

```<code><template name="machine">
    <li class="liMachine switch">
        <div id="nameMachine">
            <h3>{{nameMachine}}</h3>
        </div>
        <div id="stateMachine">
            State:<span class="state">{{stateMachine}}</span>
        </div>
        {{#if isLocked}}
        <div>
          <img class="imgCadenas">
        </div>
        {{else}}
          {{#if hideStopM}}
            {{else}}
              {{#if is_running_machine}}<i class="fa fa-spinner fa-spin"></i>
            {{else}}<button type="button" class="stop {{#if to_hide_stopM}}hidden{{/if}}"></button>
            {{/if}}
          {{/if}}

          {{#if hideKillM}}
          {{else}}
            {{#if is_alive_machine}}<i class="fa fa-spinner fa-spin"></i>
              {{else}}<button type="button" class="kill {{#if to_hide_stopM}}hidden{{/if}}"></button>
            {{/if}}
          {{/if}}

          {{#if is_stopped_machine}}<i class="fa fa-spinner fa-spin"></i>{{else}}<button type="button" class="start {{#if to_hide_startM}}hidden{{/if}}"></button>{{/if}}
        {{/if}}
    </li>
</template>
</code>```

the part I'm working on is the {{#if isLocked}}

When I use float:right I have :

When I use the solution of setting the position: absolute;top:0px..:

When I use the solution of @this.believer:

答:
add this to your CSS classes :</p>

```<code>.imgCadenas{
  z-index:5;
  position: absolute;
  right:/*some px/vw from the right side*/;
  top:/*some spx/vh from the top*/;
  bottom:/*same as above if vertically centered*/;
  left:auto;
  width:auto;
  height:auto;
}

.liMachine{
  position: relative;
}
</code>```

Body:
I want to display my locker image at the right of the div but kept the div size and format.

that's the default state:

that's what happens now when I lock:

And I want to do something like this:

To make this I made this css:

.imgCadenas{
  width:  100px;
  height: 100px;
  background: url('/cadenas.png');
  text-align: right;
  background-repeat: no-repeat;
  background-size: 100%;
}

and the HTML is not special but I put it:

<template name="machine">

{{nameMachine}}

            State:{{stateMachine}}

        {{#if isLocked}}

        {{else}}
          {{#if hideStopM}}
            {{else}}
              {{#if is_running_machine}}
            {{else}}<button type="button" class="stop {{#if to_hide_stopM}}hidden{{/if}}"></button>
            {{/if}}
          {{/if}}

          {{#if hideKillM}}
          {{else}}
            {{#if is_alive_machine}}
              {{else}}<button type="button" class="kill {{#if to_hide_stopM}}hidden{{/if}}"></button>
            {{/if}}
          {{/if}}

          {{#if is_stopped_machine}}{{else}}<button type="button" class="start {{#if to_hide_startM}}hidden{{/if}}"></button>{{/if}}
        {{/if}}

</template>

the part I'm working on is the {{#if isLocked}}

When I use float:right I have :

When I use the solution of setting the position: absolute;top:0px..:

When I use the solution of @this.believer:

Body:
add this to your CSS classes :

.imgCadenas{
  z-index:5;
  position: absolute;
  right:/*some px/vw from the right side*/;
  top:/*some spx/vh from the top*/;
  bottom:/*same as above if vertically centered*/;
  left:auto;
  width:auto;
  height:auto;
}

.liMachine{
  position: relative;
}


问:
What are some good Java web development tools (across the board)
For web development what are some standard/good java tools.  That apply to all aspects of development.

For example, The IDE (Eclipse, RAD, Intellij) is important, but what else is there.

Ant is a good one.
Cygwin, Linux OS possibly.

答:
We are using TeamCity. This is very useful tool for building projects. Supporting not only Java but also .NET projects. And it is free.

And why no one mentioned about VSC? :) We are using Subversion, but Git is more convinient in more cases. It give more comfortable tools for working with branches.

Maven also good tool, but it's too complex. Especially if you are already using ant. In this situation i recommend you to look at Ivy. Ivy can manage dependencies for you, like Maven, and use Maven repositories.

VisualVM great tool for monitoring your JVM instances. It have plugins for mbeans exploring, thread dump analyzing, memory dump analyzing and more.

As unit testing framework i recommend TestNG combining with hamcrest. TestNG is more flexible than JUnit and have multiple advantages like support for parallel testing, for example. You can easily run your tests in parallel.

OwnerDisplayName: Berlin Brown

OwnerDisplayName: dotsid


问:
Read path in level compaction strategy in Cassandra
I want to know whether a read request goes from higher levels(L3, L4, having more sstables) to lower levels(L0, L1, having lesser sstables) or the other way round.

The problem with read requests going from higher levels to lower levels is that  a row in higher level sstable may contain obsolete data if the same row in a lower level sstable have been updated and not yet compacted to the higher level. Is that understanding correct?

On the other hand, going from lower level to higher levels won't ensure 90% read guarantee from a single sstable. In most cases, it will read all the levels.

答:
Please review this:

How does the Leveled Compaction Strategy ensure 90% of reads are from one sstable

In most cases, it will read all the levels

Only if you get to state when you have same key saved in all levels. And this is worst case scenario, when you have to read 1 sstable for each level.

Leveled compaction guarantees that 90% of all reads will be satisfied
  from a single sstable (assuming nearly-uniform row size). Worst case
  is bounded at the total number of levels — e.g., 7 for 10TB of data.

http://www.datastax.com/dev/blog/leveled-compaction-in-apache-cassandra


问:
Unable to use pyexcel-xls with pyinstaller . python executable not working . python version 3.4.4
The program works when run using:

```<code>Python filename.py
</code>```

but when I create its executable file using "pyinstaller"

```<code>pyinstaller -F filename.py
</code>```

the executable is successfully created, but execution of the script fails and following error is thrown.

```<code>Traceback (most recent call last):
  File "site-packages\pyexcel_io\manager.py", line 160, in create_reader
  File "site-packages\pyexcel_io\manager.py", line 222, in _get_a_handler
pyexcel_io.manager.NoSupportingPluginFound: No suitable library found for xls

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "script.py", line 8, in <module>
  File "site-packages\pyexcel_xls\__init__.py", line 29, in get_data
  File "site-packages\pyexcel_io\io.py", line 36, in get_data
  File "site-packages\pyexcel_io\io.py", line 126, in load_data
  File "site-packages\pyexcel_io\manager.py", line 171, in create_reader
pyexcel_io.manager.SupportingPluginAvailableButNotInstalled: Please install pyexcel-xls
Failed to execute script script
</code>```

The respective python script is :

```<code>from pyexcel_xls import save_data , get_data
data = get_data("registered-market-makers-by-security.xls")
save_data("file_to_consume.xls", data)
</code>```

How can I avoid this error and create a functional .exe file?

My client has windows environment.

I have also tried py2exe but it has some conflicts with windows dll's in my machine.

答:
The Problem

pyexcel-io uses a method for including plug-ins that pyinstaller does not support.  See this issue.

The Workaround

The work around for this issue has a couple of facets.

Change needed to pyexcel

I have submitted a Change Request which shows how to modify pyexcel to allow it to work with pyinstaller.  Basically pyexcel-io needs to know how to find frozen modules.

If the pyexcel guys pick up the Change Request, then that will get you going.  But if they don't, or you are in a hurry, then copying the changed file from the change request into your site package directory as pyexcel_io/__init__.py will get pyexcel working.

But, pyinstaller also needs to know what to include.

pyinstaller also needs to know to include the required module.  So on the pyinstaller command line you will also need to do:

```<code>--hidden-import pyexcel_xls.xls
</code>```

Update:

Change request with this fix has been merged into master branch of pyexcel.

Update #2:

Fix has been released to pypi.

Body:
The program works when run using:

Python filename.py

but when I create its executable file using "pyinstaller"

pyinstaller -F filename.py

the executable is successfully created, but execution of the script fails and following error is thrown.

Traceback (most recent call last):
  File "site-packages\pyexcel_io\manager.py", line 160, in create_reader
  File "site-packages\pyexcel_io\manager.py", line 222, in _get_a_handler
pyexcel_io.manager.NoSupportingPluginFound: No suitable library found for xls

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "script.py", line 8, in <module>
  File "site-packages\pyexcel_xls\__init__.py", line 29, in get_data
  File "site-packages\pyexcel_io\io.py", line 36, in get_data
  File "site-packages\pyexcel_io\io.py", line 126, in load_data
  File "site-packages\pyexcel_io\manager.py", line 171, in create_reader
pyexcel_io.manager.SupportingPluginAvailableButNotInstalled: Please install pyexcel-xls
Failed to execute script script

The respective python script is :

from pyexcel_xls import save_data , get_data
data = get_data("registered-market-makers-by-security.xls")
save_data("file_to_consume.xls", data)

How can I avoid this error and create a functional .exe file?

My client has windows environment.

I have also tried py2exe but it has some conflicts with windows dll's in my machine.

Body:
The Problem

pyexcel-io uses a method for including plug-ins that pyinstaller does not support.  See this issue.

The Workaround

The work around for this issue has a couple of facets.

Change needed to pyexcel

I have submitted a Change Request which shows how to modify pyexcel to allow it to work with pyinstaller.  Basically pyexcel-io needs to know how to find frozen modules.

If the pyexcel guys pick up the Change Request, then that will get you going.  But if they don't, or you are in a hurry, then copying the changed file from the change request into your site package directory as pyexcel_io/__init__.py will get pyexcel working.

But, pyinstaller also needs to know what to include.

pyinstaller also needs to know to include the required module.  So on the pyinstaller command line you will also need to do:

--hidden-import pyexcel_xls.xls

Update:

Change request with this fix has been merged into master branch of pyexcel.

Update #2:

Fix has been released to pypi.


问:
CNTK: How to define UpSampling2D
I'm wondering how to achieve UpSampling2D in CNTK. I cannot find such layer in the API.

UpSampling2D is an opposite operation of pooling layers, and expand the data by repeating the rows and columns of the data. Here's keras/tensorflow API for UpSampling2D.

By looking at the tensorflow code, they use backend.resize_images operation, but I cannot find resize operation in CNTK API either.

Answer 1 (From Frank)

Answer 2 (From David)

Picture from Quora: How do fully convolutional networks upsample their coarse output?

答:
It can be assembled from basic operations of reshaping and splicing, e.g.</p>

```<code>>>> x = Input((3, 480, 640))
>>> xr = reshape(x, (3, 480, 1, 640, 1))
>>> xr.shape
(3, 480, 1, 640, 1)
>>> xx = splice(xr, xr, axis=-1) # axis=-1 refers to the last axis
>>> xx.shape
(3, 480, 1, 640, 2)
>>> xy = splice(xx, xx, axis=-3) # axis=-3 refers to the middle axis
>>> xy.shape
(3, 480, 2, 640, 2)
>>> r = reshape(xy, (3, 480*2, 640*2))
>>> r.shape
(3, 960, 1280)
</code>```

Title: CNTK: How to define UpSampling2D

Body:
It can be assembled from basic operations of reshaping and splicing, e.g.

>>> x = Input((3, 480, 640))
>>> xr = reshape(x, (3, 480, 1, 640, 1))
>>> xr.shape
(3, 480, 1, 640, 1)
>>> xx = splice(xr, xr, axis=-1) # axis=-1 refers to the last axis
>>> xx.shape
(3, 480, 1, 640, 2)
>>> xy = splice(xx, xx, axis=-3) # axis=-3 refers to the middle axis
>>> xy.shape
(3, 480, 2, 640, 2)
>>> r = reshape(xy, (3, 480*2, 640*2))
>>> r.shape
(3, 960, 1280)


问:
Incorrect time saved during event execution
I have an event which saves data to table:

```<code>CREATE DEFINER=`root`@`i2` EVENT `AcrhiveData` ON SCHEDULE EVERY 5
                MINUTE STARTS '2017-03-13 10:45:00' ON COMPLETION NOT PRESERVE ENABLE DO
INSERT INTO `archived`(`projectNo`, `staff_id`, `longname`, `username`, `title`, `process`, `creation_time`)
SELECT a.*
FROM
(
    (
        SELECT p.projectNo,
               usr.staff_id,
               usr.longname,
               usr.username,
               p.title,
               CONCAT(upr.process, " (", upr.role, ")" ) AS process,
               NOW() AS creation_time
        FROM project p
        INNER JOIN user_project upr
            ON p.projectNo = upr.projectNo
        INNER JOIN user usr
            ON upr.username = usr.username
        WHERE EXISTS (SELECT status FROM check_change WHERE status = "1" )
    )
) AS a
ORDER BY a.projectNo
</code>```

it works but the problem is incorrect time in NOW(). if i save it at 2017-03-29-10:50:00 on my pc event will save it as 2017-03-29 02:50:00
What is the problem and how can I solve this?

答:
ok, thats how i solved the problem:

instead of NOW() AS creation_time I used DATE_ADD(UTC_TIMESTAMP(), INTERVAL 8 HOUR) AS creation_time

Body:
I have an event which saves data to table:

CREATE DEFINER=`root`@`i2` EVENT `AcrhiveData` ON SCHEDULE EVERY 5
                MINUTE STARTS '2017-03-13 10:45:00' ON COMPLETION NOT PRESERVE ENABLE DO
INSERT INTO `archived`(`projectNo`, `staff_id`, `longname`, `username`, `title`, `process`, `creation_time`)
SELECT a.*
FROM
(
    (
        SELECT p.projectNo,
               usr.staff_id,
               usr.longname,
               usr.username,
               p.title,
               CONCAT(upr.process, " (", upr.role, ")" ) AS process,
               NOW() AS creation_time
        FROM project p
        INNER JOIN user_project upr
            ON p.projectNo = upr.projectNo
        INNER JOIN user usr
            ON upr.username = usr.username
        WHERE EXISTS (SELECT status FROM check_change WHERE status = "1" )
    )
) AS a
ORDER BY a.projectNo

it works but the problem is incorrect time in NOW(). if i save it at 2017-03-29-10:50:00 on my pc event will save it as 2017-03-29 02:50:00
What is the problem and how can I solve this?


问:
ested exception is org.hibernate.exception.GenericJDBCException: could not execute query
I am using Spring JPA Repository,Not able to execute query

Here is my java code :

```<code>public interface TbBamiVacationRepository extends JpaRepository<TbBamiVacation,String>{
    @Modifying
    @Query(value = "select user_id,reassign_to from tb_bami_vacation a where to_date1 >=to_date(:toDate, 'DD-MON-YYYY') and to_date(:toDate, 'DD-MON-YYYY') >=from_date and to_date(:toDate, 'DD-MON-YYYY') <=to_date1 and user_id='112'",nativeQuery=true)
    List<TbBamiVacation> findReassignedTo( @Param("toDate")String toDate);
                                      //toDate="26-MAR-2017"
}
</code>```

My Logs:

```<code>Hibernate: select user_id,reassign_to from tb_bami_vacation a where to_date1 >=to_date(?, 'DD-MON-YYYY') and to_date(?, 'DD-MON-YYYY') >=from_date and to_date(?, 'DD-MON-YYYY') <=to_date1 and user_id='112'

org.springframework.orm.jpa.JpaSystemException: could not execute query; nested exception is org.hibernate.exception.GenericJDBCException: could not execute query
at org.springframework.orm.jpa.vendor.HibernateJpaDialect.convertHibernateAccessException(HibernateJpaDialect.java:244)
at org.springframework.orm.jpa.vendor.HibernateJpaDialect.translateExceptionIfPossible(HibernateJpaDialect.java:155)
at org.springframework.orm.jpa.AbstractEntityManagerFactoryBean.translateExceptionIfPossible(AbstractEntityManagerFactoryBean.java:417)
at org.springframework.dao.support.ChainedPersistenceExceptionTranslator.translateExceptionIfPossible(ChainedPersistenceExceptionTranslator.java:59)
at org.springframework.dao.support.DataAccessUtils.translateIfNecessary(DataAccessUtils.java:213)
at org.springframework.dao.support.PersistenceExceptionTranslationInterceptor.invoke(PersistenceExceptionTranslationInterceptor.java:147)
at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:179)
at org.springframework.data.jpa.repository.support.CrudMethodMetadataPostProcessor$CrudMethodMetadataPopulatingMethodIntercceptor.invoke(CrudMethodMetadataPostProcessor.java:111)

Caused by: java.sql.SQLException: Invalid column name
at oracle.jdbc.driver.OracleStatement.getColumnIndex(OracleStatement.java:3677)
at oracle.jdbc.driver.OracleResultSetImpl.findColumn(OracleResultSetImpl.java:2749)
at oracle.jdbc.driver.OracleResultSet.getString(OracleResultSet.java:494)
at org.apache.tomcat.dbcp.dbcp2.DelegatingResultSet.getString(DelegatingResultSet.java:266)
at org.apache.tomcat.dbcp.dbcp2.DelegatingResultSet.getString(DelegatingResultSet.java:266)
</code>```

Thanks in advance !!

答:
Remove 'a' from here:

```<code>from tb_bami_vacation a where
</code>```

Change:

```<code>@Param("toDate")
</code>```

to:

```<code>@Param("to_date1")
</code>```

Body:
I am using Spring JPA Repository,Not able to execute query

Here is my java code :

public interface TbBamiVacationRepository extends JpaRepository<TbBamiVacation,String>{
    @Modifying
    @Query(value = "select user_id,reassign_to from tb_bami_vacation a where to_date1 >=to_date(:toDate, 'DD-MON-YYYY') and to_date(:toDate, 'DD-MON-YYYY') >=from_date and to_date(:toDate, 'DD-MON-YYYY') <=to_date1 and user_id='112'",nativeQuery=true)
    List<TbBamiVacation> findReassignedTo( @Param("toDate")String toDate);
                                      //toDate="26-MAR-2017"
}

My Logs:

Hibernate: select user_id,reassign_to from tb_bami_vacation a where to_date1 >=to_date(?, 'DD-MON-YYYY') and to_date(?, 'DD-MON-YYYY') >=from_date and to_date(?, 'DD-MON-YYYY') <=to_date1 and user_id='112'

org.springframework.orm.jpa.JpaSystemException: could not execute query; nested exception is org.hibernate.exception.GenericJDBCException: could not execute query
at org.springframework.orm.jpa.vendor.HibernateJpaDialect.convertHibernateAccessException(HibernateJpaDialect.java:244)
at org.springframework.orm.jpa.vendor.HibernateJpaDialect.translateExceptionIfPossible(HibernateJpaDialect.java:155)
at org.springframework.orm.jpa.AbstractEntityManagerFactoryBean.translateExceptionIfPossible(AbstractEntityManagerFactoryBean.java:417)
at org.springframework.dao.support.ChainedPersistenceExceptionTranslator.translateExceptionIfPossible(ChainedPersistenceExceptionTranslator.java:59)
at org.springframework.dao.support.DataAccessUtils.translateIfNecessary(DataAccessUtils.java:213)
at org.springframework.dao.support.PersistenceExceptionTranslationInterceptor.invoke(PersistenceExceptionTranslationInterceptor.java:147)
at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:179)
at org.springframework.data.jpa.repository.support.CrudMethodMetadataPostProcessor$CrudMethodMetadataPopulatingMethodIntercceptor.invoke(CrudMethodMetadataPostProcessor.java:111)

Caused by: java.sql.SQLException: Invalid column name
at oracle.jdbc.driver.OracleStatement.getColumnIndex(OracleStatement.java:3677)
at oracle.jdbc.driver.OracleResultSetImpl.findColumn(OracleResultSetImpl.java:2749)
at oracle.jdbc.driver.OracleResultSet.getString(OracleResultSet.java:494)
at org.apache.tomcat.dbcp.dbcp2.DelegatingResultSet.getString(DelegatingResultSet.java:266)
at org.apache.tomcat.dbcp.dbcp2.DelegatingResultSet.getString(DelegatingResultSet.java:266)

Thanks in advance !!

Body:
Remove 'a' from here:

from tb_bami_vacation a where

Change:

@Param("toDate")

to:

@Param("to_date1")


问:
Server returned HTTP response code: 415 Unsupported media type
I have a rest web service like below.

```<code>@POST
@Path("/startProcess")
@Produces(MediaType.TEXT_PLAIN)
@Consumes(MediaType.APPLICATION_JSON)
public String startProcess(InputParams inputParams, @Context HttpServletRequest request, @Context HttpServletResponse response) {
   ProjectBean projBean = new ProjectBean();
   Helper.loadProjectBean(inputParams, projBean);
   return "1";
}
</code>```

Now I am trying to consume it with below main program.

```<code>public static void main(String[] args) throws Exception {
    StringBuffer response = new StringBuffer();
    String taigaServiceUrl = "http://localhost:8181/restServer/rest/TestWebService/startProcess/";
    URL url = new URL(taigaServiceUrl);
    HttpURLConnection conn = (HttpURLConnection) url.openConnection();
    conn.setRequestMethod("POST");
    conn.setDoOutput(true);
    conn.setRequestProperty("Content-Type", "application/json");
    String userpass = "admin" + ":" + "admin";
    String basicAuth = "Basic " + new String(new Base64().encode(userpass.getBytes()));
    conn.setRequestProperty("Authorization", basicAuth);
    InputParams inputParams = new InputParams();
    inputParams.setXXX("xxxx");
    inputParams.setYYYY("123456");
    inputParams.setZZZZ("ZZZZ");
    String json = new Gson().toJson(inputParams);
    DataOutputStream os = new DataOutputStream (conn.getOutputStream());
    os.write(json.getBytes());
    os.flush();
    BufferedReader br = new BufferedReader(new InputStreamReader((conn.getInputStream())));
    String inputLine;
    while ((inputLine = br.readLine()) != null) {
        response.append(inputLine);
    }
    br.close();
}
</code>```

But every time I am getting below error.

```<code>Exception in thread "main" java.io.IOException: Server returned HTTP response code: 415 for URL: http://localhost:8181/restServer/rest/TestWebService/startProcess/
at sun.net.www.protocol.http.HttpURLConnection.getInputStream0(Unknown Source)
at sun.net.www.protocol.http.HttpURLConnection.getInputStream(Unknown Source)
at scm.controllers.Test.main(Test.java:64)
</code>```

As per error the media type is unsupported. In my rest webservice I am consuming JSON and in my main program I am sending JSON. Then where it is breaking?

答:
Have a look at this guide:

I think you need to define a json processor:

```<code>https://www.nabisoft.com/tutorials/java-ee/producing-and-consuming-json-or-xml-in-java-rest-services-with-jersey-and-jackson
</code>```

thanks.

Body:
I have a rest web service like below.

@POST
@Path("/startProcess")
@Produces(MediaType.TEXT_PLAIN)
@Consumes(MediaType.APPLICATION_JSON)
public String startProcess(InputParams inputParams, @Context HttpServletRequest request, @Context HttpServletResponse response) {
   ProjectBean projBean = new ProjectBean();
   Helper.loadProjectBean(inputParams, projBean);
   return "1";
}

Now I am trying to consume it with below main program.

public static void main(String[] args) throws Exception {
    StringBuffer response = new StringBuffer();
    String taigaServiceUrl = "http://localhost:8181/restServer/rest/TestWebService/startProcess/";
    URL url = new URL(taigaServiceUrl);
    HttpURLConnection conn = (HttpURLConnection) url.openConnection();
    conn.setRequestMethod("POST");
    conn.setDoOutput(true);
    conn.setRequestProperty("Content-Type", "application/json");
    String userpass = "admin" + ":" + "admin";
    String basicAuth = "Basic " + new String(new Base64().encode(userpass.getBytes()));
    conn.setRequestProperty("Authorization", basicAuth);
    InputParams inputParams = new InputParams();
    inputParams.setXXX("xxxx");
    inputParams.setYYYY("123456");
    inputParams.setZZZZ("ZZZZ");
    String json = new Gson().toJson(inputParams);
    DataOutputStream os = new DataOutputStream (conn.getOutputStream());
    os.write(json.getBytes());
    os.flush();
    BufferedReader br = new BufferedReader(new InputStreamReader((conn.getInputStream())));
    String inputLine;
    while ((inputLine = br.readLine()) != null) {
        response.append(inputLine);
    }
    br.close();
}

But every time I am getting below error.

Exception in thread "main" java.io.IOException: Server returned HTTP response code: 415 for URL: http://localhost:8181/restServer/rest/TestWebService/startProcess/
at sun.net.www.protocol.http.HttpURLConnection.getInputStream0(Unknown Source)
at sun.net.www.protocol.http.HttpURLConnection.getInputStream(Unknown Source)
at scm.controllers.Test.main(Test.java:64)

As per error the media type is unsupported. In my rest webservice I am consuming JSON and in my main program I am sending JSON. Then where it is breaking?

Body:
Have a look at this guide:

I think you need to define a json processor:

https://www.nabisoft.com/tutorials/java-ee/producing-and-consuming-json-or-xml-in-java-rest-services-with-jersey-and-jackson

thanks.


问:
Why do I need a $watch when using function in controller in combination with a directive
I know and can imagine why I need the commented lines of code to let this work. But I can't found the technical reason. Why is the field not update when you click on the button? (the $watch fixed the problem. See comments)

Code:

angular.module('app', []).directive('foo', function() {
    return {
            scope: {
                value: '='
            },
            link: function($scope, element){
              element.html($scope.value);
              //$scope.$watch(function() { return $scope.value }, function(){
               //element.html($scope.value);
               //})
            }
        };
}).controller('FooController', ['$scope', function($scope) {
  $scope.bar = "Hi"

   $scope.sayHallo = function(){
     return $scope.bar;
    }

    $scope.changeHallo = function(){
     $scope.bar = "Héj";
    }
}]);```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="app">
    <div ng-controller="FooController">
        <div foo value="sayHallo()" ></div>
        <button ng-click="changeHallo()">
            Click
        </button>
    </div>
</div></code>```

答:
This change may help you

HTML

```<code><div ng-controller="FooController">
    <div foo value="bar"></div>
    <button ng-click="changeHallo()">
      Click
    </button>
  </div>
</code>```

Jsfiddle demo

Body:
I know and can imagine why I need the commented lines of code to let this work. But I can't found the technical reason. Why is the field not update when you click on the button? (the $watch fixed the problem. See comments)

Code:

angular.module('app', []).directive('foo', function() {
    return {
            scope: {
                value: '='
            },
            link: function($scope, element){
              element.html($scope.value);
              //$scope.$watch(function() { return $scope.value }, function(){
               //element.html($scope.value);
               //})
            }
        };
}).controller('FooController', ['$scope', function($scope) {
  $scope.bar = "Hi"

   $scope.sayHallo = function(){
     return $scope.bar;
    }

    $scope.changeHallo = function(){
     $scope.bar = "Héj";
    }
}]);

        <button ng-click="changeHallo()">
            Click
        </button>

Body:
This change may help you

HTML

<div ng-controller="FooController">
    <div foo value="bar"></div>
    <button ng-click="changeHallo()">
      Click
    </button>
  </div>

Jsfiddle demo


问:
Get data using post request in REST API Codeigniter
I am working with REST API for the first time in codeigniter.
I have following function in api

```<code> public function cource_topics_post() {
        $username = $this->input->post('username');
        //$value=$this->uri->segment(3);
        $this->response(array('status' => 1, 'username' =>  $username ));
    }
</code>```

but

```<code>$username = $this->input->post('username');
</code>```

isn't working. need help

My controller is as follows

```<code>    <?php

header("Access-Control-Allow-Origin: *");
require(APPPATH . '/libraries/REST_Controller.php');

class Admin extends REST_Controller {
    function __construct() {
        parent::__construct();
        $this->load->helper('file');
        $this->load->helper(array('form', 'url'));
    }

    public function cource_topics_post() {
        $username = $this->post('username');
        $password = $this->post('password');
        //$value=$this->uri->segment(3);
        $user = "faizan";
        $pass = "faizan";
        if($username == $user && $password == $pass){
            $this->response(array('status' => 1, 'logged in as' =>  $username ));
        }
        else{
            $this->response(array('status' => 0, 'Could not login' => 'incorrect username password'));
        }
    }

}
</code>```

I am using rest_controller.

答: Make sure you have extended CI_Controller class in your class

Body:
I am working with REST API for the first time in codeigniter.
I have following function in api

 public function cource_topics_post() {
        $username = $this->input->post('username');
        //$value=$this->uri->segment(3);
        $this->response(array('status' => 1, 'username' =>  $username ));
    }

but

$username = $this->input->post('username');

isn't working. need help

My controller is as follows

    <?php

header("Access-Control-Allow-Origin: *");
require(APPPATH . '/libraries/REST_Controller.php');

class Admin extends REST_Controller {
    function __construct() {
        parent::__construct();
        $this->load->helper('file');
        $this->load->helper(array('form', 'url'));
    }

    public function cource_topics_post() {
        $username = $this->post('username');
        $password = $this->post('password');
        //$value=$this->uri->segment(3);
        $user = "faizan";
        $pass = "faizan";
        if($username == $user && $password == $pass){
            $this->response(array('status' => 1, 'logged in as' =>  $username ));
        }
        else{
            $this->response(array('status' => 0, 'Could not login' => 'incorrect username password'));
        }
    }

}

I am using rest_controller.


问:
Install Nuget package solution wide
I build a Nuget package that copies some sepcific files to a directory in my solution directory. The directory is not included in the Solution itself, it only stores some files which are to be used by some projects in my solution.

Now my problem ist that I have to choose the projects in which the package is to be installed. But I don't want it to be included in all of my projects as the only job of the package is to distribute files globally.

Is it not possible at all to install a Nuget package for the solution itself?

答:
Solution-wide packages have been deprecated, as explained in this comment:

We deprecated solution level packages in NuGet 3.0 and we don't plan to support them going forward.

There were plans on restoring them in the future, unfortunately these plans had been cancelled:

no plan to bring this back for now. Dotnet tools (available with 15.7 shortly) will bridge this gap.
https://github.com/dotnet/cli/issues/5147#issuecomment-359836475

Workarounds include:

external scripts

a fake project that acts as a representative for the solution node on the project level

GetNuTool

Title: Install Nuget package solution wide

ContentLicense: CC BY-SA 4.0


问:
PHP web service for command line users
I have been given a task to write a web service to push data from sensors to the server database.

I have written a PHP webservice which takes some arguments in GET, process the data in it and stores the data in the database.

Example

```<code>http://www.example.com/pushDataService/index.php?arg1=<Data 1>&arg2=<Data 2>&arg3=<Data 3>
</code>```

But our firmware programmer wants something that he can test on a command line.
Just like SMTP communication using telnet

Example

```<code>Telnet mail.example.com 25
EHLO mail.example.com
AUTH LOGIN
UserName encrypted in base 64
Password encrypted in base 64
MAIL FROM:<test@example.com>
RCPT TO:<test@domain.com>
DATA this is a test message.
</code>```

Can I make the webservice work like this where he can do the handshaking process in command line and then each argument is sent individually and user get a response for each argument ?

Please help, I am new to PHP and have no idea of (web) service like this!

Thank you

Edit:
We are already using MQTT to push the data to the server but we need another server to push data which will work as a combination of SMTP mail server and MQTT protocol...
Will a SOAP web service do the job for me?

答:
The http://www.example.com/pushDataService/index.php?arg1=<Data 1>&arg2=<Data 2>&arg3=<Data 3> request can be done Just like SMTP communication using telnet as following:

```<code>Telnet www.example.com 80
GET /pushDataService/index.php?arg1=<Data 1>&arg2=<Data 2>&arg3=<Data 3> HTTP/1.1
Host: www.example.com
<CR>
<CR>
</code>```

Pushing data with GET requests is not the best idea. PUT or POST requests would be more suitable. First of all it is not idempotent and should never be cached, and what is more important - it is way more flexible in data format and size. The POST request sending json data may look like

```<code>Telnet www.example.com 80
POST /pushDataService/index.php HTTP/1.1
Host: www.example.com
Content-Type: application/json; charset=utf-8
Content-Length: 57

{"arg1":"<Data 1>", "arg2":"<Data 2>", "arg3":"<Data 3>"}
</code>```

Title: PHP web service for command line users

Body:
I have been given a task to write a web service to push data from sensors to the server database.

I have written a PHP webservice which takes some arguments in GET, process the data in it and stores the data in the database.

Example

http://www.example.com/pushDataService/index.php?arg1=<Data 1>&arg2=<Data 2>&arg3=<Data 3>

But our firmware programmer wants something that he can test on a command line.
Just like SMTP communication using telnet

Example

Telnet mail.example.com 25
EHLO mail.example.com
AUTH LOGIN
UserName encrypted in base 64
Password encrypted in base 64
MAIL FROM:<test@example.com>
RCPT TO:<test@domain.com>
DATA this is a test message.

Can I make the webservice work like this where he can do the handshaking process in command line and then each argument is sent individually and user get a response for each argument ?

Please help, I am new to PHP and have no idea of (web) service like this!

Thank you

Edit:
We are already using MQTT to push the data to the server but we need another server to push data which will work as a combination of SMTP mail server and MQTT protocol...
Will a SOAP web service do the job for me?

Body:
The http://www.example.com/pushDataService/index.php?arg1=<Data 1>&arg2=<Data 2>&arg3=<Data 3> request can be done Just like SMTP communication using telnet as following:

Telnet www.example.com 80
GET /pushDataService/index.php?arg1=<Data 1>&arg2=<Data 2>&arg3=<Data 3> HTTP/1.1
Host: www.example.com
<CR>
<CR>

Pushing data with GET requests is not the best idea. PUT or POST requests would be more suitable. First of all it is not idempotent and should never be cached, and what is more important - it is way more flexible in data format and size. The POST request sending json data may look like

Telnet www.example.com 80
POST /pushDataService/index.php HTTP/1.1
Host: www.example.com
Content-Type: application/json; charset=utf-8
Content-Length: 57

{"arg1":"<Data 1>", "arg2":"<Data 2>", "arg3":"<Data 3>"}


问:
Horizontally center images which overflows their container
I am trying to center some images (horizontally) which overflows their container divs.

The containers (and images, for that matter) have a height of 160px and I want to keep them with that height, even at smaller screen-sizes - but still keep the image horizontally centered.

I have tried margin: 0 auto; with no luck.

I came across an half-solution where it was suggested to use text-align: center; on the container div along with margin: 0 -100%; on the image itself. However this solution seems to only work with webkit based browsers.

In eg. Firefox the result is this:

HTML:

```<code><div class="row-fluid">
    <div class="span6">
        <a>
            <img src="image1.jpg">
        </a>
    </div>
    <div class="span6">
        <a>
            <img src="image2.jpg">
        </a>
    </div>
</div>
</code>```

CSS:

```<code>.span6{
    height: 160px;
    overflow: hidden;
    text-align: center;
    padding: 0;
}

.span6 img{
    height: 160px;
    width: auto;
    margin: 0 -100%; /*Only works for webkit based browsers*/
}
</code>```

Any ideas? Thank you in advance.

.

EDIT:

I found out that editing margin: 0 -100%; to margin: 0 -50%; did the trick (both in Chrome, Firefox, IE, etc). However I am going with Andrey's solution since it is more likely cleaner, I assume.

答:
May be this will help</p>

```<code>.span {
    display: flex;
    align-items: center;
    justify-content: center;
}
</code>```

Body:
I am trying to center some images (horizontally) which overflows their container divs.

The containers (and images, for that matter) have a height of 160px and I want to keep them with that height, even at smaller screen-sizes - but still keep the image horizontally centered.

I have tried margin: 0 auto; with no luck.

I came across an half-solution where it was suggested to use text-align: center; on the container div along with margin: 0 -100%; on the image itself. However this solution seems to only work with webkit based browsers.

In eg. Firefox the result is this:

HTML:

CSS:

.span6{
    height: 160px;
    overflow: hidden;
    text-align: center;
    padding: 0;
}

.span6 img{
    height: 160px;
    width: auto;
    margin: 0 -100%; /*Only works for webkit based browsers*/
}

Any ideas? Thank you in advance.

.

EDIT:

I found out that editing margin: 0 -100%; to margin: 0 -50%; did the trick (both in Chrome, Firefox, IE, etc). However I am going with Andrey's solution since it is more likely cleaner, I assume.

Body:
May be this will help

.span {
    display: flex;
    align-items: center;
    justify-content: center;
}


问:
Display Exceptions in ASP.NET / Azure
I have a custom error page in an Azure ASP.NET web app where I'd like to display

```<code>   <p>Oops - something went wrong.</p>
<p>The most common problem is that you tried to do something that the database enforces shouldn't happen.</p>
<p>The error is:</p>
</code>```

In web.config I have:

```<code><customErrors mode="On" defaultRedirect="Error.aspx" />
</code>```

and global.asax:

```<code>protected void Application_Error(object sender, EventArgs e)
        {
            Exception objErr = Server.GetLastError().GetBaseException();
            string err = "Error Caught in Application_Error event\n" +
                    "Error in: " + Request.Url.ToString() +
                    "\nError Message:" + objErr.Message.ToString() +
                    "\nStack Trace:" + objErr.StackTrace.ToString();
            EventLog.WriteEntry("Sample_WebApp", err, EventLogEntryType.Error);
        }
</code>```

Problem: How to display the full exception on the Error.aspx page?

答:
Try adding redirectMode="ResponseRewrite" attribute to the customErrors element if you are using ASP.NET 3.5 SP1. That should preserve the exception information stored in Server.GetLastError(). Then you can add a label to the Error.aspx page and display the exception details, i.e. lblError.Text = Server.GetLastError().ToString().

Here's a similar SO question: ASP.NET custom error page - Server.GetLastError() is null

Title: Display Exceptions in ASP.NET / Azure

Body:
I have a custom error page in an Azure ASP.NET web app where I'd like to display

Oops - something went wrong.

The most common problem is that you tried to do something that the database enforces shouldn't happen.

The error is:

In web.config I have:

<customErrors mode="On" defaultRedirect="Error.aspx" />

and global.asax:

protected void Application_Error(object sender, EventArgs e)
        {
            Exception objErr = Server.GetLastError().GetBaseException();
            string err = "Error Caught in Application_Error event\n" +
                    "Error in: " + Request.Url.ToString() +
                    "\nError Message:" + objErr.Message.ToString() +
                    "\nStack Trace:" + objErr.StackTrace.ToString();
            EventLog.WriteEntry("Sample_WebApp", err, EventLogEntryType.Error);
        }

Problem: How to display the full exception on the Error.aspx page?


问:
Mvc Dynamic Menu Populating plain text
I have created the N'th level Dynamic Menu recursive method which creates a menu.

As seen in above picture the content is returned to ParialView named "_Menu.cshtml" and this Partial View file is empty.

and then there is a _LayoutPage.Cshtml

```<code>    <!DOCTYPE html>

<html>
<head>
    <meta name="viewport" content="width=device-width" />
    <title>@ViewBag.Title</title>
</head>
<body>
    <div>
        <div>
            <input type="text" id="txtSearch" />
            <button id="btnSearch">Search</button>
         </div>
        <div id="Menu">
            @{Html.RenderAction("_Menu", "Home"); }
            @Html.Partial("_Menu")
        </div>
        <div>
            @RenderBody()
        </div>
    </div>
</body>
</html>
</code>```

it successfully puts the result into the browser but as a plain text as i mentioned above and can be seen below.

How can i make these act like links, not like a plaintext? Help will be appreciated. Thanks :)

答:
I took a slightly more involved view on this one.

In the layout I put ...

```<code> @if (Model != null && Model is Core.Objects.Entities.CMS.Page)
 {
                @Html.Action("Menu", new MenuOptions { IsRootMenu = true, ForPageId = Model.Id, Depth = 3 })
 }
</code>```

I first check if the user is logged in and thus "on a managed page" which only happens if the model is of a specific type "Core.Objects.Entities.CMS.Page".

I then call @Html.Action which calls the following child action on my controller, and I construct my menu options ...

```<code>[HttpGet]
[ChildActionOnly]
[Route("~/Menu")]
public ActionResult Menu(MenuOptions options)
{
    //TODO: consider other complex menuing scenarios like a popup / tree based structures
    //      New api calls may be needed to support more complex menuing scenarios

    // TODO: figure out how to build these, perhaps with a string builder
    var expand = string.Empty;
    if (options.Depth > 0)
    {
        switch (options.Depth)
        {
            case 1: expand = "?$expand=PageInfo,Pages($expand=PageInfo)"; break;
            case 2: expand = "?$expand=PageInfo,Pages($expand=PageInfo,Pages($expand=PageInfo))"; break;
            case 3: expand = "?$expand=PageInfo,Pages($expand=PageInfo,Pages($expand=PageInfo,Pages($expand=PageInfo)))"; break;
            case 4: expand = "?$expand=PageInfo,Pages($expand=PageInfo,Pages($expand=PageInfo,Pages($expand=Pages($expand=PageInfo))))"; break;
            case 5: expand = "?$expand=PageInfo,Pages($expand=PageInfo,Pages($expand=PageInfo,Pages($expand=PageInfo,Pages($expand=PageInfo,Pages($expand=PageInfo)))))"; break;
        }
    }

    var query = options.IsRootMenu
        ? "Core/Page/MainMenuFor(id=" + options.ForPageId + ")" + expand
        : "Core/Page/ChildrenOf(id=" + options.ForPageId + ")" + expand;

    var items = Task.Run(() => Api.GetODataCollection<Page>(query)).Result;

    return PartialView(new MenuViewModel { Origin = options.ForPageId, Pages = items });
}
</code>```

In my case this area needs a little work and I should probably replace that case statement with some smarter looping code that builds the query.

In short though all this does is pull a hierarchy of Page objects off my OData API to the depth determined by my options passed in as menus tend to vary, some are single level options others go multiple levels but I wanted a reusable menuing system.

Having done that I can take the OData result and build out a model for a menu view which looks like this ...

```<code>@model MenuViewModel
@if (Model.Pages != null)
{
    <ul class="menu">
        @foreach (var p in Model.Pages)
        {
            Html.RenderPartial("MenuItem", new MenuItemViewModel { Page = p, Origin = Model.Origin });
        }
    </ul>
}
</code>```

Menu views setup a list for the root and render a child for each child page, I plan to expand on this view at some point for things like spitting out the parent page which could be in the OData result I pulled in the controller.

And the final piece of the puzzle is the menu item view that deals with rendering each individual menu item ...

```<code>@model MenuItemViewModel
<li>
    <a href="@Html.Raw("/" + Model.Page.Path)" @CurrentItem(Model.Page)>@Html.PageInfo(Model.Page).Title</a>
    @if (Model.Page.Pages != null && Model.Page.Pages.Any())
    {
        <ul class="submenu">
        @foreach (var p in Model.Page.Pages)
        {
            Html.RenderPartial("MenuItem", new MenuItemViewModel { Page = p, Origin = Model.Origin });
        }
        </ul>
    }
</li>

@functions{
    MvcHtmlString CurrentItem(Core.Objects.Entities.CMS.Page p)
    {
        if (Model.Origin == p.Id) return new MvcHtmlString("class='selected'");
        return null;
    }
}
</code>```

Having done all this I end up with essentially a nested set of lists I then use CSS to handle things like popups or dynamic expands ect.

This functionality is not quite complete, I need to make sure I handle "marking the current item" with a class or something so I can style it differently and there are a few other menuing scenarios I would like to add, but also I have considered reusing this html structure in some way for tree views but trees may be a bit more involved in the longer term but doing things like putting an image next to menu items seems like a nice logical improvement if its configurable :)

One last thing I forgot to put in before is the menu options model used on the Menu action in the controller ...

```<code>public class MenuOptions
{
    public bool IsRootMenu { get; set; }
    public int ForPageId { get; set; }
    public int Depth { get; set; }
}
</code>```

Title: Mvc Dynamic Menu Populating plain text

Body:
I have created the N'th level Dynamic Menu recursive method which creates a menu.

As seen in above picture the content is returned to ParialView named "_Menu.cshtml" and this Partial View file is empty.

and then there is a _LayoutPage.Cshtml

    <!DOCTYPE html>

    <meta name="viewport" content="width=device-width" />
    <title>@ViewBag.Title</title>

            <input type="text" id="txtSearch" />
            <button id="btnSearch">Search</button>

            @{Html.RenderAction("_Menu", "Home"); }
            @Html.Partial("_Menu")

            @RenderBody()

it successfully puts the result into the browser but as a plain text as i mentioned above and can be seen below.

How can i make these act like links, not like a plaintext? Help will be appreciated. Thanks :)

Body:
I took a slightly more involved view on this one.

In the layout I put ...

 @if (Model != null && Model is Core.Objects.Entities.CMS.Page)
 {
                @Html.Action("Menu", new MenuOptions { IsRootMenu = true, ForPageId = Model.Id, Depth = 3 })
 }

I first check if the user is logged in and thus "on a managed page" which only happens if the model is of a specific type "Core.Objects.Entities.CMS.Page".

I then call @Html.Action which calls the following child action on my controller, and I construct my menu options ...

[HttpGet]
[ChildActionOnly]
[Route("~/Menu")]
public ActionResult Menu(MenuOptions options)
{
    //TODO: consider other complex menuing scenarios like a popup / tree based structures
    //      New api calls may be needed to support more complex menuing scenarios

    // TODO: figure out how to build these, perhaps with a string builder
    var expand = string.Empty;
    if (options.Depth > 0)
    {
        switch (options.Depth)
        {
            case 1: expand = "?$expand=PageInfo,Pages($expand=PageInfo)"; break;
            case 2: expand = "?$expand=PageInfo,Pages($expand=PageInfo,Pages($expand=PageInfo))"; break;
            case 3: expand = "?$expand=PageInfo,Pages($expand=PageInfo,Pages($expand=PageInfo,Pages($expand=PageInfo)))"; break;
            case 4: expand = "?$expand=PageInfo,Pages($expand=PageInfo,Pages($expand=PageInfo,Pages($expand=Pages($expand=PageInfo))))"; break;
            case 5: expand = "?$expand=PageInfo,Pages($expand=PageInfo,Pages($expand=PageInfo,Pages($expand=PageInfo,Pages($expand=PageInfo,Pages($expand=PageInfo)))))"; break;
        }
    }

    var query = options.IsRootMenu
        ? "Core/Page/MainMenuFor(id=" + options.ForPageId + ")" + expand
        : "Core/Page/ChildrenOf(id=" + options.ForPageId + ")" + expand;

    var items = Task.Run(() => Api.GetODataCollection<Page>(query)).Result;

    return PartialView(new MenuViewModel { Origin = options.ForPageId, Pages = items });
}

In my case this area needs a little work and I should probably replace that case statement with some smarter looping code that builds the query.

In short though all this does is pull a hierarchy of Page objects off my OData API to the depth determined by my options passed in as menus tend to vary, some are single level options others go multiple levels but I wanted a reusable menuing system.

Having done that I can take the OData result and build out a model for a menu view which looks like this ...

@model MenuViewModel
@if (Model.Pages != null)
{
    <ul class="menu">
        @foreach (var p in Model.Pages)
        {
            Html.RenderPartial("MenuItem", new MenuItemViewModel { Page = p, Origin = Model.Origin });
        }
    </ul>
}

Menu views setup a list for the root and render a child for each child page, I plan to expand on this view at some point for things like spitting out the parent page which could be in the OData result I pulled in the controller.

And the final piece of the puzzle is the menu item view that deals with rendering each individual menu item ...

@model MenuItemViewModel
<li>
    <a href="@Html.Raw("/" + Model.Page.Path)" @CurrentItem(Model.Page)>@Html.PageInfo(Model.Page).Title</a>
    @if (Model.Page.Pages != null && Model.Page.Pages.Any())
    {
        <ul class="submenu">
        @foreach (var p in Model.Page.Pages)
        {
            Html.RenderPartial("MenuItem", new MenuItemViewModel { Page = p, Origin = Model.Origin });
        }
        </ul>
    }
</li>

@functions{
    MvcHtmlString CurrentItem(Core.Objects.Entities.CMS.Page p)
    {
        if (Model.Origin == p.Id) return new MvcHtmlString("class='selected'");
        return null;
    }
}

Having done all this I end up with essentially a nested set of lists I then use CSS to handle things like popups or dynamic expands ect.

This functionality is not quite complete, I need to make sure I handle "marking the current item" with a class or something so I can style it differently and there are a few other menuing scenarios I would like to add, but also I have considered reusing this html structure in some way for tree views but trees may be a bit more involved in the longer term but doing things like putting an image next to menu items seems like a nice logical improvement if its configurable :)

One last thing I forgot to put in before is the menu options model used on the Menu action in the controller ...

public class MenuOptions
{
    public bool IsRootMenu { get; set; }
    public int ForPageId { get; set; }
    public int Depth { get; set; }
}


问:
Dynamic method name inside a class?
I'd like to, when instantiating a class to be able to pass to it a name that will be used for prefixing a method name in that class, so far I have this

```<code><?php
if ( ! class_exists( 'My_Class' ) ) {
    /**
     * Creates filter method
     *
     * @since  1.0.0
     */
    class My_Class {

        /**
         * Prefix for method names
         *
         * @var string $name Name of the filter prefix.
         */
        private $name;

        /**
         * Version.
         *
         * @var string
         */
        private $version = '1.0.0';

        /**
         * Initialize the class and set its properties.
         *
         * @since 1.0.0
         * @param string $name    The name for the method prefix.
         * @param string $version The version of this plugin.
         */
        public function __construct( $name, $version ) {
            $this->name = $name;
            $this->version = $version;
            add_filter( 'my_filter_name', $name . '_my_folder' );
        }

        /**
         * Function for filtering folder array
         *
         * Each plugin has to set its own array of paths and url.
         *
         * @param  array $import_array Array with folder values.
         * @return array               Modified array with folder values.
         */
        public function $name . _my_folder() {
            $import_array[$this->name]['folder']     = plugin_dir_path( __FILE__ ) . 'includes/layout';
            $import_array[$this->name]['folder_url'] = plugin_dir_url( __FILE__ ) . 'includes/layout';
            return $import_array;
        }

    }
}
</code>```

The idea is that I'd just call it like

```<code>$first_object = new My_Class( 'first' );
$second_object = new My_Class( 'second' );
</code>```

This is so that I can use this in multiple same plugins, with different names, depending on the type of the plugin.

The obvious problem is function $name . _my_folder().

I read something about __call() magic method but I'm not sure if this can be used in this case, or how to apply it.

Can this be done?

答:
Why don't you make name parameter of the method?

Like this:

```<code>add_filter('my_filter_name', [$this, 'methodName'], 10, 1);
</code>```

third parameter is priority of filter, and fourth is number of accepted args.

```<code>public function methodName($name) {}
</code>```

and call it like this:

```<code>apply_filters('my_filter_name', $value, $arg);
</code>```

Title: Dynamic method name inside a class?

Body:
I'd like to, when instantiating a class to be able to pass to it a name that will be used for prefixing a method name in that class, so far I have this

<?php
if ( ! class_exists( 'My_Class' ) ) {
    /**
     * Creates filter method
     *
     * @since  1.0.0
     */
    class My_Class {

        /**
         * Prefix for method names
         *
         * @var string $name Name of the filter prefix.
         */
        private $name;

        /**
         * Version.
         *
         * @var string
         */
        private $version = '1.0.0';

        /**
         * Initialize the class and set its properties.
         *
         * @since 1.0.0
         * @param string $name    The name for the method prefix.
         * @param string $version The version of this plugin.
         */
        public function __construct( $name, $version ) {
            $this->name = $name;
            $this->version = $version;
            add_filter( 'my_filter_name', $name . '_my_folder' );
        }

        /**
         * Function for filtering folder array
         *
         * Each plugin has to set its own array of paths and url.
         *
         * @param  array $import_array Array with folder values.
         * @return array               Modified array with folder values.
         */
        public function $name . _my_folder() {
            $import_array[$this->name]['folder']     = plugin_dir_path( __FILE__ ) . 'includes/layout';
            $import_array[$this->name]['folder_url'] = plugin_dir_url( __FILE__ ) . 'includes/layout';
            return $import_array;
        }

    }
}

The idea is that I'd just call it like

$first_object = new My_Class( 'first' );
$second_object = new My_Class( 'second' );

This is so that I can use this in multiple same plugins, with different names, depending on the type of the plugin.

The obvious problem is function $name . _my_folder().

I read something about __call() magic method but I'm not sure if this can be used in this case, or how to apply it.

Can this be done?

Body:
Why don't you make name parameter of the method?

Like this:

add_filter('my_filter_name', [$this, 'methodName'], 10, 1);

third parameter is priority of filter, and fourth is number of accepted args.

public function methodName($name) {}

and call it like this:

apply_filters('my_filter_name', $value, $arg);


问:
how to create a fake rails' `request` object to test a gem with rspec
I am developing a gem, which one of its functions will authenticate the incoming request to the controller, and I want to test it. but I don't know how can I fake a rails' request object and send it to the function to test its behavior, who can I do this?

答: I guess you need https://github.com/bblimke/webmock or its analogs</p>


问:
How to create form with 2 relations to different tables
I have 3 tables. One of them is "visit" table, which links to "Patients" and "Type of Visit".

I want to create form where you can fill up, visit data, and select patient and "type of visit", and if there is no patient that you need you should have the ability to create one (the same with type of visit).

I tried to do it with subforms, but I just cannot find a way to connect things.

I understand SQL, but I have no knowledge of how forms work in MS Access.

Thank you in advance.

答:
Conventional data entry options for many-to-many relationship:

single form bound to table 3 with comboboxes to select items from tables 1 and 2

main form bound to table 2 and subform bound to table 3 with combobox to select items from table 1

main form bound to table 1 and subform bound to table 3 with combobox to select items from table 2

If you want to be able to add items to table that is source for combobox 'on-the-fly' during data entry, look into the combobox NotInList event. Combobox NotInList Event


问:
Error :app:installDebug FAILED when run android app, how to solve it?
I try run test app from here https://github.com/Singree/react-native-example-app but when I type react-native run-android I get error in :app:installDebug, log here https://pastebin.com/063Np2GX android-studio emulator is launched, how to solve it?

答: Try this adb reverse tcp:8081 tcp:8081 the execute command if still failed you should go for bundle it and sign it then deploy to device