text:
Q: How can I copy non-contiguous cells from a workbook to a different set of non-contiguous cells in another workbook? I have a Master blank workbook that users copy, to record one year's worth of information.  The Master blank allows the user to point to last year's 'old' workbook, insert the proper number of rows into the new to match the old, and then copy/paste two different contiguous ranges from the old into matching ranges in the "new" blank workbook.
Now, I want it to copy the values that are the totals from non-contiguous columns on the old worksheet into different non-contiguous cells on the new worksheet.
The totals are on a different row for each user so I use a lastrow function to find the row number.  But it seems I cannot use that in defining the non-contiguous ranges.
All the code is included below.  You will notice a section where I'm trying to copy all of the data from an old worksheet into the new worksheet using Union on ranges because it too is a bunch of non-contiguous cells, but it's not working either.  If I get the first problem solved, I should be able to adapt it to the second problem.
Edit:
I modified the "union" section and now all of the correct cells are being selected but Selection.Copy fails.  What's the alternative?
Edit #2:
I added two screenshots of the Master blank and a user's file.  It is easy to see a) the number of rows is different and b) the shaded areas are the ones I wish to copy/paste (in the 'union' section of code).  In the next pair of screenshots, the red and green cells of the user's file need to be imported into the corresponding red and green cells of the Master blank file.
Option Explicit
Sub UpdateFromOld()

Dim fd As FileDialog
Dim NewWbk As Workbook, OldWbk As Workbook
Dim vrtSelectedItem As Variant, fname As Variant
Dim cella As Range, cellb As Range, cell1 As Range, cell2 As Range
Dim wsh As Worksheet, wsh2 As Worksheet
Dim WshName As String, WshName2 As String
Dim Answer1 As String, Answer2 As String
Dim UsedRange1 As Range, UsedRange2 As Range
Dim InputRange As Range, InputRange1 As Range, InputRange2 As Range, InputRange3 As Range, InputRange4 As Range, InputRange5 As Range
Dim InputRange6 As Range, InputRange7 As Range, InputRange8 As Range, InputRange9 As Range, InputRange10 As Range, InputRange11 As Range
Dim LstYr, ThisYr
Dim ExtraRows As Integer, RowCounter As Integer
Dim SumArray1(24)
Dim MyCell1, cell

On Error GoTo ErrorHandler

Range("B5").Select
WshName = InputBox("Type in your location name", "Annual Ad Planner")
Range("B5").Value = WshName
ActiveSheet.Name = WshName
Set wsh = Worksheets(WshName)

'Application.ScreenUpdating = False

'select the old file to update from
MsgBox "In the next window, navigate to and select the Ad Planner file you are updating from.", vbOKOnly, "Annual Ad Planner"
Set fd = Application.FileDialog(msoFileDialogFilePicker)
With fd
    .Filters.Add "Previous Ad Planner", "*.xls", 1
    If .Show = -1 Then
        For Each vrtSelectedItem In .SelectedItems
            fname = vrtSelectedItem
        Next vrtSelectedItem
    Else
        MsgBox "You ended the update process.", vbOKOnly, "Annual Ad Planner"
        GoTo ErrorHandler
    End If
End With

Set OldWbk = Workbooks.Open(fname)
OldWbk.Unprotect
Set NewWbk = ThisWorkbook
NewWbk.Unprotect
Set fd = Nothing

NewWbk.Worksheets(WshName).Visible = True
NewWbk.Worksheets(WshName).Activate
NewWbk.Worksheets(WshName).Unprotect
Set cella = Cells(Rows.Count, "A").End(xlUp).Offset(0, 0)

OldWbk.Activate
Range("B5").Select
WshName2 = ActiveCell.Worksheet.Name
Set wsh2 = Worksheets(WshName2)
OldWbk.Worksheets(WshName2).Visible = True
OldWbk.Worksheets(WshName2).Activate
OldWbk.Worksheets(WshName2).Unprotect
Set cellb = Cells(Rows.Count, "B").End(xlUp).Offset(0, 0)

Range("B5").Select
Selection.Copy
NewWbk.Activate
Range("B5").Select
Range("B5").PasteSpecial xlPasteValues

Range("B23").Select
If cellb.Row > cella Then
    ExtraRows = cellb.Row - cella
    For RowCounter = 1 To ExtraRows
        AddRow
    Next RowCounter
End If
NewWbk.Unprotect
NewWbk.Worksheets(WshName).Unprotect

'Copy & Paste list of lead sources
OldWbk.Activate
Range("B20:B" & cellb.Row - 1).Select
Selection.Copy
NewWbk.Activate
Range("B20").Select
Range("B20").PasteSpecial xlPasteValues

'Copy & Paste classifications & segments
OldWbk.Activate
Range("CI20:CK" & cellb.Row - 1).Select
Selection.Copy
NewWbk.Activate
Range("CI20").Select
Range("CI20").PasteSpecial xlPasteValues
Application.CutCopyMode = False

Answer1 = MsgBox("Are you importing last year's file?", vbYesNoCancel, "Annual Ad Planner")
If Answer1 = vbNo Then
    Answer2 = MsgBox("Are you updating the 2014 file?", vbYesNoCancel, "Annual Ad Planner")
    If Answer2 = vbYes Then
        Set InputRange = Union(Range("C3"), Range("C4"), Range("C6"), Range("C7"), Range("C9"), Range("E6"), Range("E7"), Range("E9"), Range("J3"), Range("J4"), Range("J6"), Range("J7"), Range("J9"), Range("L6"), Range("L7"), Range("L9"), Range("Q3"), Range("Q4"), Range("Q6"), Range("Q7"), Range("Q9"), Range("S6"), Range("S7"), Range("S9"), Range("X3"), Range("X4"), Range("X6"), Range("X7"), Range("X9"), Range("Z6")) '30 ranges
        Set InputRange1 = Union(Range("Z7"), Range("Z9"), Range("AE3"), Range("AE4"), Range("AE6"), Range("AE7"), Range("AE9"), Range("AG6"), Range("AG7"), Range("AG9"), Range("AL3"), Range("AL4"), Range("AL6"), Range("AL7"), Range("AL9"), Range("AN6"), Range("AN7"), Range("AN9"), Range("AS3"), Range("AS4"), Range("AS6"), Range("AS7"), Range("AS9"), Range("AU6"), Range("AU7"), Range("AU9"), Range("AZ3"), Range("AZ4")) '28 ranges
        Set InputRange2 = Union(Range("AZ6"), Range("AZ7"), Range("AZ9"), Range("BB6"), Range("BB7"), Range("BB9"), Range("BG3"), Range("BG4"), Range("BG6"), Range("BG7"), Range("BG9"), Range("BI6"), Range("BI7"), Range("BI9"), Range("BN3"), Range("BN4"), Range("BN6"), Range("BN7"), Range("BN9"), Range("BP6"), Range("BP7"), Range("BP9"), Range("BU3"), Range("BU4"), Range("BU6"), Range("BU7"), Range("BU9"), Range("BW6")) '28 ranges
        Set InputRange3 = Union(Range("BW7"), Range("BW9"), Range("CB3"), Range("CB4"), Range("CB6"), Range("CB7"), Range("CB9"), Range("CD6")) '8 ranges
        Set InputRange4 = Union(Range("CD7"), Range("CD9"), Range("C20:D" & cellb.Row - 1), Range("F20:G" & cellb.Row - 1), Range("J20:K" & cellb.Row - 1), Range("M20:N" & cellb.Row - 1), Range("Q20:R" & cellb.Row - 1), Range("T20:U" & cellb.Row - 1), Range("X20:Y" & cellb.Row - 1), Range("AA20:AB" & cellb.Row - 1), Range("AE20:AF" & cellb.Row - 1), Range("AH20:AI" & cellb.Row - 1), Range("AL20:AM" & cellb.Row - 1), Range("AO20:AP" & cellb.Row - 1), Range("AS20:AT" & cellb.Row - 1), Range("AV20:AW" & cellb.Row - 1), Range("AZ20:BA" & cellb.Row - 1), Range("BC20:BD" & cellb.Row - 1), Range("BG20:BH" & cellb.Row - 1), Range("BJ20:BK" & cellb.Row - 1), Range("BN20:BO" & cellb.Row - 1), Range("BQ20:BR" & cellb.Row - 1), Range("BU20:BV" & cellb.Row - 1), Range("BX20:BY" & cellb.Row - 1), Range("CB20:CC" & cellb.Row - 1), Range("CE20:CF" & cellb.Row - 1)) ' 26 ranges with unknown # of cells
        Set InputRange5 = Union(InputRange, InputRange1, InputRange2, InputRange3, InputRange4)
        OldWbk.Activate
        Set InputRange6 = Union(Range("C3"), Range("C4"), Range("C6"), Range("C7"), Range("C9"), Range("E6"), Range("E7"), Range("E9"), Range("J3"), Range("J4"), Range("J6"), Range("J7"), Range("J9"), Range("L6"), Range("L7"), Range("L9"), Range("Q3"), Range("Q4"), Range("Q6"), Range("Q7"), Range("Q9"), Range("S6"), Range("S7"), Range("S9"), Range("X3"), Range("X4"), Range("X6"), Range("X7"), Range("X9"), Range("Z6")) '30 ranges
        Set InputRange7 = Union(Range("Z7"), Range("Z9"), Range("AE3"), Range("AE4"), Range("AE6"), Range("AE7"), Range("AE9"), Range("AG6"), Range("AG7"), Range("AG9"), Range("AL3"), Range("AL4"), Range("AL6"), Range("AL7"), Range("AL9"), Range("AN6"), Range("AN7"), Range("AN9"), Range("AS3"), Range("AS4"), Range("AS6"), Range("AS7"), Range("AS9"), Range("AU6"), Range("AU7"), Range("AU9"), Range("AZ3"), Range("AZ4")) '28 ranges
        Set InputRange8 = Union(Range("AZ6"), Range("AZ7"), Range("AZ9"), Range("BB6"), Range("BB7"), Range("BB9"), Range("BG3"), Range("BG4"), Range("BG6"), Range("BG7"), Range("BG9"), Range("BI6"), Range("BI7"), Range("BI9"), Range("BN3"), Range("BN4"), Range("BN6"), Range("BN7"), Range("BN9"), Range("BP6"), Range("BP7"), Range("BP9"), Range("BU3"), Range("BU4"), Range("BU6"), Range("BU7"), Range("BU9"), Range("BW6")) '28 ranges
        Set InputRange9 = Union(Range("BW7"), Range("BW9"), Range("CB3"), Range("CB4"), Range("CB6"), Range("CB7"), Range("CB9"), Range("CD6")) '8 ranges
        Set InputRange10 = Union(Range("CD7"), Range("CD9"), Range("C20:D" & cellb.Row - 1), Range("F20:G" & cellb.Row - 1), Range("J20:K" & cellb.Row - 1), Range("M20:N" & cellb.Row - 1), Range("Q20:R" & cellb.Row - 1), Range("T20:U" & cellb.Row - 1), Range("X20:Y" & cellb.Row - 1), Range("AA20:AB" & cellb.Row - 1), Range("AE20:AF" & cellb.Row - 1), Range("AH20:AI" & cellb.Row - 1), Range("AL20:AM" & cellb.Row - 1), Range("AO20:AP" & cellb.Row - 1), Range("AS20:AT" & cellb.Row - 1), Range("AV20:AW" & cellb.Row - 1), Range("AZ20:BA" & cellb.Row - 1), Range("BC20:BD" & cellb.Row - 1), Range("BG20:BH" & cellb.Row - 1), Range("BJ20:BK" & cellb.Row - 1), Range("BN20:BO" & cellb.Row - 1), Range("BQ20:BR" & cellb.Row - 1), Range("BU20:BV" & cellb.Row - 1), Range("BX20:BY" & cellb.Row - 1), Range("CB20:CC" & cellb.Row - 1), Range("CE20:CF" & cellb.Row - 1)) ' 26 ranges with unknown # of cells
        Set InputRange11 = Union(InputRange6, InputRange7, InputRange8, InputRange9, InputRange10)
        InputRange11.Select
        Selection.Copy
        NewWbk.Activate
        InputRange5.Select
        Selection.PasteSpecial xlPasteValues
    Else
    End If
ElseIf Answer1 = vbYes Then
    Set LstYr = OldWbk.Worksheets(WshName2).Range("F" & cellb.Row, "G" & cellb.Row, "M" & cellb.Row, "N" & cellb.Row, "T" & cellb.Row, "U" & cellb.Row, "AA" & cellb.Row, "AB" & cellb.Row, "AH" & cellb.Row, "AI" & cellb.Row, "AO" & cellb.Row, "AP" & cellb.Row, "AV" & cellb.Row, "AW" & cellb.Row, "BC" & cellb.Row, "BD" & cellb.Row, "BJ" & cellb.Row, "BK" & cellb.Row, "BQ" & cellb.Row, "BR" & cellb.Row, "BX" & cellb.Row, "BY" & cellb.Row, "CE" & cellb.Row, "CF" & cellb.Row)  '24 ranges
    Set ThisYr = NewWbk.Worksheets(WshName).Range("C3, C4, J3, J4, Q3, Q4, X3, X4, AE3, AE4, AL3, AL4, AS3, AS4, AZ3, AZ4, BG3, BG4, BN3, BN4, BU3, BU4, CB3, CB4") '24 ranges
    OldWbk.Activate
    OldWbk.Worksheets(WshName2).Range("F" & cellb.Row).Select

    For MyCell1 = 1 To 24
        SumArray1(MyCell1) = 0
    Next MyCell1
    MyCell1 = 1

    For Each cell In LstYr
        SumArray1(MyCell1) = cell.Value
        MyCell1 = MyCell1 = 1
    Next cell

    NewWbk.Activate
    MyCell1 = 1
    For Each cell In ThisYr
        cell.Value = SumArray1(MyCell1)
        MyCell1 = MyCell1 = 1
    Next cell
End If
OldWbk.Close SaveChanges:=False
NewWbk.Protect

Application.ScreenUpdating = True

ErrorHandler:
    Resume Next

End Sub

[screenshots hosted on flickr] http://www.flickr.com/photos/32470349@N03/11873809585/

A: The answer L42 provided wouldn't work for my situation, and is definitely a viable solution for situations similar to how he imagined it.
My final working code is shown below.  The section below the series of "InputRange" unions that starts with ElseIf Answer1 = vbYes Then is how I solved the non-contiguous question posted.
Option Explicit
Sub UpdateFromOld()

    Dim fd As FileDialog
    Dim NewWbk As Workbook, OldWbk As Workbook
    Dim vrtSelectedItem As Variant, fname As Variant
    Dim cella As Range, cellb As Range, cell1 As Range, cell2 As Range
    Dim cell As Range, PasteRng As Range
    Dim wsh As Worksheet, wsh2 As Worksheet
    Dim WshName As String, WshName2 As String, MyDate As String
    Dim Answer1 As String, Answer2 As String
    Dim UsedRange1 As Range, UsedRange2 As Range
    Dim InputRange As Range, InputRange1 As Range, InputRange2 As Range, InputRange3 As Range, InputRange4 As Range, InputRange5 As Range
    Dim InputRange6 As Range, InputRange7 As Range, InputRange8 As Range, InputRange9 As Range, InputRange10 As Range, InputRange11 As Range
    Dim LstYr1 As Range, LstYr2 As Range, ThisYr1 As Range, ThisYr2 As Range
    Dim ExtraRows As Integer, RowCounter As Integer
    Dim SumArray1(12)
    Dim MyCell1

    On Error GoTo ErrorHandler

    Range("B5").Select
    WshName = InputBox("Type in your location name", "Annual Ad Planner")
    MyDate = InputBox("Enter the year you are working on in YYYY format.", "Annual Ad Planner")
    Set NewWbk = ThisWorkbook
    NewWbk.Unprotect
    ActiveSheet.Unprotect
    Range("A6").Value = "1/10/" & MyDate
    Range("B5").Value = WshName
    ActiveSheet.Name = WshName
    Set wsh = NewWbk.Worksheets(WshName)

    'Application.ScreenUpdating = False

    'select the old file to update from
    MsgBox "In the next window, navigate to and select the Ad Planner file you are updating from.", vbOKOnly, "Annual Ad Planner"
    Set fd = Application.FileDialog(msoFileDialogFilePicker)
    With fd
        .Filters.Add "Previous Ad Planner", "*.xls", 1
        If .Show = -1 Then
            For Each vrtSelectedItem In .SelectedItems
                fname = vrtSelectedItem
            Next vrtSelectedItem
        Else
            MsgBox "You ended the update process.", vbOKOnly, "Annual Ad Planner"
            GoTo ErrorHandler
        End If
    End With

    Set OldWbk = Workbooks.Open(fname)
    OldWbk.Unprotect
    Set fd = Nothing

    NewWbk.Worksheets(WshName).Visible = True
    NewWbk.Worksheets(WshName).Activate
    NewWbk.Worksheets(WshName).Unprotect
    Set cella = Cells(Rows.Count, "A").End(xlUp).Offset(0, 0)
    Range("A" & cella.Row).Select

    OldWbk.Activate
    Range("B5").Select
    WshName2 = ActiveCell.Worksheet.Name
    Set wsh2 = Worksheets(WshName2)
    OldWbk.Worksheets(WshName2).Visible = True
    OldWbk.Worksheets(WshName2).Activate
    OldWbk.Worksheets(WshName2).Unprotect
    Set cellb = Cells(Rows.Count, "A").End(xlUp).Offset(0, 0)
    Range("A" & cellb.Row).Select

    Range("B5").Select
    Selection.Copy
    NewWbk.Activate
    Range("B5").Select
    Range("B5").PasteSpecial xlPasteValues

    Range("B23").Select
    If cellb.Row > cella Then
        ExtraRows = cellb.Row - cella
        For RowCounter = 1 To ExtraRows
            AddRow
        Next RowCounter
    End If
    NewWbk.Unprotect
    NewWbk.Worksheets(WshName).Unprotect

    'Copy & Paste list of lead sources
    OldWbk.Activate
    Range("B20:B" & cellb.Row - 1).Select
    Selection.Copy
    NewWbk.Activate
    Range("B20").Select
    Range("B20").PasteSpecial xlPasteValues

    'Copy & Paste classifications & segments
    OldWbk.Activate
    Range("CI20:CK" & cellb.Row - 1).Select
    Selection.Copy
    NewWbk.Activate
    Range("CI20").Select
    Range("CI20").PasteSpecial xlPasteValues
    Application.CutCopyMode = False

    Answer1 = MsgBox("Are you importing sources and totals from last year's file?", vbYesNoCancel, "Annual Ad Planner")
    If Answer1 = vbNo Then
        Answer2 = MsgBox("Are you updating the current file to the new format?", vbYesNoCancel, "Annual Ad Planner")
        If Answer2 = vbYes Then
            Set InputRange = Union(Range("C3"), Range("C4"), Range("C6"), Range("C7"), Range("C9"), Range("E6"), Range("E7"), Range("E9"), Range("J3"), Range("J4"), Range("J6"), Range("J7"), Range("J9"), Range("L6"), Range("L7"), Range("L9"), Range("Q3"), Range("Q4"), Range("Q6"), Range("Q7"), Range("Q9"), Range("S6"), Range("S7"), Range("S9"), Range("X3"), Range("X4"), Range("X6"), Range("X7"), Range("X9"), Range("Z6")) '30 ranges
            Set InputRange1 = Union(Range("Z7"), Range("Z9"), Range("AE3"), Range("AE4"), Range("AE6"), Range("AE7"), Range("AE9"), Range("AG6"), Range("AG7"), Range("AG9"), Range("AL3"), Range("AL4"), Range("AL6"), Range("AL7"), Range("AL9"), Range("AN6"), Range("AN7"), Range("AN9"), Range("AS3"), Range("AS4"), Range("AS6"), Range("AS7"), Range("AS9"), Range("AU6"), Range("AU7"), Range("AU9"), Range("AZ3"), Range("AZ4")) '28 ranges
            Set InputRange2 = Union(Range("AZ6"), Range("AZ7"), Range("AZ9"), Range("BB6"), Range("BB7"), Range("BB9"), Range("BG3"), Range("BG4"), Range("BG6"), Range("BG7"), Range("BG9"), Range("BI6"), Range("BI7"), Range("BI9"), Range("BN3"), Range("BN4"), Range("BN6"), Range("BN7"), Range("BN9"), Range("BP6"), Range("BP7"), Range("BP9"), Range("BU3"), Range("BU4"), Range("BU6"), Range("BU7"), Range("BU9"), Range("BW6")) '28 ranges
            Set InputRange3 = Union(Range("BW7"), Range("BW9"), Range("CB3"), Range("CB4"), Range("CB6"), Range("CB7"), Range("CB9"), Range("CD6")) '8 ranges
            Set InputRange4 = Union(Range("CD7"), Range("CD9"), Range("C20:D" & cellb.Row - 1), Range("F20:G" & cellb.Row - 1), Range("J20:K" & cellb.Row - 1), Range("M20:N" & cellb.Row - 1), Range("Q20:R" & cellb.Row - 1), Range("T20:U" & cellb.Row - 1), Range("X20:Y" & cellb.Row - 1), Range("AA20:AB" & cellb.Row - 1), Range("AE20:AF" & cellb.Row - 1), Range("AH20:AI" & cellb.Row - 1), Range("AL20:AM" & cellb.Row - 1), Range("AO20:AP" & cellb.Row - 1), Range("AS20:AT" & cellb.Row - 1), Range("AV20:AW" & cellb.Row - 1), Range("AZ20:BA" & cellb.Row - 1), Range("BC20:BD" & cellb.Row - 1), Range("BG20:BH" & cellb.Row - 1), Range("BJ20:BK" & cellb.Row - 1), Range("BN20:BO" & cellb.Row - 1), Range("BQ20:BR" & cellb.Row - 1), Range("BU20:BV" & cellb.Row - 1), Range("BX20:BY" & cellb.Row - 1), Range("CB20:CC" & cellb.Row - 1), Range("CE20:CF" & cellb.Row - 1)) ' 26 ranges with unknown # of cells
            Set InputRange5 = Union(InputRange, InputRange1, InputRange2, InputRange3, InputRange4)
            OldWbk.Activate
            Set InputRange6 = Union(Range("C3"), Range("C4"), Range("C6"), Range("C7"), Range("C9"), Range("E6"), Range("E7"), Range("E9"), Range("J3"), Range("J4"), Range("J6"), Range("J7"), Range("J9"), Range("L6"), Range("L7"), Range("L9"), Range("Q3"), Range("Q4"), Range("Q6"), Range("Q7"), Range("Q9"), Range("S6"), Range("S7"), Range("S9"), Range("X3"), Range("X4"), Range("X6"), Range("X7"), Range("X9"), Range("Z6")) '30 ranges
            Set InputRange7 = Union(Range("Z7"), Range("Z9"), Range("AE3"), Range("AE4"), Range("AE6"), Range("AE7"), Range("AE9"), Range("AG6"), Range("AG7"), Range("AG9"), Range("AL3"), Range("AL4"), Range("AL6"), Range("AL7"), Range("AL9"), Range("AN6"), Range("AN7"), Range("AN9"), Range("AS3"), Range("AS4"), Range("AS6"), Range("AS7"), Range("AS9"), Range("AU6"), Range("AU7"), Range("AU9"), Range("AZ3"), Range("AZ4")) '28 ranges
            Set InputRange8 = Union(Range("AZ6"), Range("AZ7"), Range("AZ9"), Range("BB6"), Range("BB7"), Range("BB9"), Range("BG3"), Range("BG4"), Range("BG6"), Range("BG7"), Range("BG9"), Range("BI6"), Range("BI7"), Range("BI9"), Range("BN3"), Range("BN4"), Range("BN6"), Range("BN7"), Range("BN9"), Range("BP6"), Range("BP7"), Range("BP9"), Range("BU3"), Range("BU4"), Range("BU6"), Range("BU7"), Range("BU9"), Range("BW6")) '28 ranges
            Set InputRange9 = Union(Range("BW7"), Range("BW9"), Range("CB3"), Range("CB4"), Range("CB6"), Range("CB7"), Range("CB9"), Range("CD6")) '8 ranges
            Set InputRange10 = Union(Range("CD7"), Range("CD9"), Range("C20:D" & cellb.Row - 1), Range("F20:G" & cellb.Row - 1), Range("J20:K" & cellb.Row - 1), Range("M20:N" & cellb.Row - 1), Range("Q20:R" & cellb.Row - 1), Range("T20:U" & cellb.Row - 1), Range("X20:Y" & cellb.Row - 1), Range("AA20:AB" & cellb.Row - 1), Range("AE20:AF" & cellb.Row - 1), Range("AH20:AI" & cellb.Row - 1), Range("AL20:AM" & cellb.Row - 1), Range("AO20:AP" & cellb.Row - 1), Range("AS20:AT" & cellb.Row - 1), Range("AV20:AW" & cellb.Row - 1), Range("AZ20:BA" & cellb.Row - 1), Range("BC20:BD" & cellb.Row - 1), Range("BG20:BH" & cellb.Row - 1), Range("BJ20:BK" & cellb.Row - 1), Range("BN20:BO" & cellb.Row - 1), Range("BQ20:BR" & cellb.Row - 1), Range("BU20:BV" & cellb.Row - 1), Range("BX20:BY" & cellb.Row - 1), Range("CB20:CC" & cellb.Row - 1), Range("CE20:CF" & cellb.Row - 1)) ' 26 ranges with unknown # of cells
            Set InputRange11 = Union(InputRange6, InputRange7, InputRange8, InputRange9, InputRange10)
            InputRange11.Select
            For Each cell In InputRange11
                OldWbk.Activate
                InputRange5.Range(cell.Address).Offset(-2, -2).Value = InputRange11.Range(cell.Address).Offset(-2, -2).Value
            Next
            NewWbk.Activate
            Range("B5").Value = WshName
        Else
        End If
    ElseIf Answer1 = vbYes Then
        OldWbk.Activate
        Set LstYr1 = Union(Range("F" & cellb.Row - 10), Range("M" & cellb.Row - 10), Range("T" & cellb.Row - 10), Range("AA" & cellb.Row - 10), Range("AH" & cellb.Row - 10), Range("AO" & cellb.Row - 10), Range("AV" & cellb.Row - 10), Range("BC" & cellb.Row - 10), Range("BJ" & cellb.Row - 10), Range("BQ" & cellb.Row - 10), Range("BX" & cellb.Row - 10), Range("CE" & cellb.Row - 10))  '12 ranges
        Set LstYr2 = Union(Range("G" & cellb.Row - 10), Range("N" & cellb.Row - 10), Range("U" & cellb.Row - 10), Range("AB" & cellb.Row - 10), Range("AI" & cellb.Row - 10), Range("AP" & cellb.Row - 10), Range("AW" & cellb.Row - 10), Range("BD" & cellb.Row - 10), Range("BK" & cellb.Row - 10), Range("BR" & cellb.Row - 10), Range("BY" & cellb.Row - 10), Range("CF" & cellb.Row - 10))  '12 ranges
        NewWbk.Activate
        Set ThisYr1 = Union(Range("C3"), Range("J3"), Range("Q3"), Range("X3"), Range("AE3"), Range("AL3"), Range("AS3"), Range("AZ3"), Range("BG3"), Range("BN3"), Range("BU3"), Range("CB3")) '24 ranges
        Set ThisYr2 = Union(Range("C4"), Range("J4"), Range("Q4"), Range("X4"), Range("AE4"), Range("AL4"), Range("AS4"), Range("AZ4"), Range("BG4"), Range("BN4"), Range("BU4"), Range("CB4")) '24 ranges

        For MyCell1 = 1 To 12
            SumArray1(MyCell1) = 0
        Next MyCell1
        MyCell1 = 1

        OldWbk.Activate
        For Each cell In LstYr1
            Range(cell.Address).Select
            SumArray1(MyCell1) = cell.Value
            MyCell1 = MyCell1 + 1
        Next cell

        MyCell1 = 1
        NewWbk.Activate
        For Each cell2 In ThisYr2
            Range(cell2.Address).Select
            cell2.Value = SumArray1(MyCell1)
            MyCell1 = MyCell1 + 1
        Next cell2

        For MyCell1 = 1 To 12
            SumArray1(MyCell1) = 0
        Next MyCell1
        MyCell1 = 1

        OldWbk.Activate
        For Each cell In LstYr2
            Range(cell.Address).Select
            SumArray1(MyCell1) = cell.Value
            MyCell1 = MyCell1 + 1
        Next cell

        MyCell1 = 1
        NewWbk.Activate
        For Each cell2 In ThisYr1
            Range(cell2.Address).Select
            cell2.Value = SumArray1(MyCell1)
            MyCell1 = MyCell1 + 1
        Next cell2

        NewWbk.Activate
        Range("B5").Value = WshName

    End If
    OldWbk.Close SaveChanges:=False
    NewWbk.Protect
    ActiveSheet.Protect
    Range("C3").Select

    Application.ScreenUpdating = True

ErrorHandler:
        Resume Next

End Sub

A: Upon checking your code, i found out that you really are copying and pasting the entire selection from the Old Wb to the New Wb at exactly the same address right?
I'm not going to answer your question directly but if above statement is true, you can use this approach:
Suppose you have data like this as your source:

And you want to paste data in another workbook with this data:

Then you can use this approach:
Sub test()

Dim copyRng As Range, cel As Range, _
    pasteRng As Range

Set copyRng = ThisWorkbook.Sheets("Sheet1").Range("B2,B4,C3,D5:E5")
Set pasteRng = ThisWorkbook.Sheets("Sheet2").Range("A1")

For Each cel In copyRng
    cel.Copy
    pasteRng.Range(cel.Address).PasteSpecial xlPasteValues
Next
Application.CutCopyMode = False
End Sub

The result will be like this:

Hope this gets you started on what you want to accomplish.
And I don't think you need to use Union at all.


text:
Q: PHP If Both Variables are 0 Why is it echoing 'both variables 0'
https://3v4l.org/E530h
<?php

  $QuantityOrdered = '1';
  $QuantityShipped = '0';
  echo '
' . $QuantityOrdered . ' & ' . $QuantityShipped . '
';

  if ($QuantityOrdered != '0' && $QuantityShipped != '0') {
    echo 'at least one variable is not 0';
  }

  else {
    echo 'both variables 0';
  }

Trying to get it so that if BOTH $QuantityOrdered and $QuantityShipped are 0, it goes to the else statement.
If $QuantityOrdered and $QuantityShipped are anything other than BOTH 0... for example, 0 and 1 (as in my example).. or 1 and 1, 2 and 2 etc...
anything other than both being 0, it goes to the if statement.

A: you need to use OR condition like this, if you use && (and) condition then both condition need to true so if $QuantityOrdered != '0' true and $QuantityShipped != '0' true then execute this code so your both condition need to true
so this condition not work
 if ($QuantityOrdered != '0' && $QuantityShipped != '0') {
  echo 'at least one variable is not 0';
}

if you want to check one value true then execute this code then use or (||) condition
if ($QuantityOrdered != '0'|| $QuantityShipped != '0') {
  echo 'at least one variable is not 0';
}
else {
 echo 'both variables 0';
 }

for more information
http://www.w3resource.com/php/operators/logical-operators.php

A: A common way to visualise logical conditions like this is as a truth table:
  | 0 | 1
--+------
0 |   |
--+---+--
1 |   |

Across the top, we have the possible values of $QuantityOrdered; down the side, the values of $QuantityShipped. In the grid, we put the result of the expression; I'll use T for true and F for false.
For your current condition, $QuantityOrdered != '0' && $QuantityShipped != '0', we get this:
  | 0 | 1
--+------
0 | F | F
--+---+--
1 | F | T

We are using 1 to mean "not 0", so the only combination that's true in our table is where both variables are 1.
But what you actually wanted was this:
  | 0 | 1
--+------
0 | F | T
--+---+--
1 | T | T

You wanted the condition to be true in all cases except for one, the case where both variables are 0.
One way to write this would be to start with the opposite. For $QuantityOrdered == '0' && $QuantityShipped == '0' we get this:
  | 0 | 1
--+------
0 | T | F
--+---+--
1 | F | F

So we could write ! ( $QuantityOrdered == '0' && $QuantityShipped == '0' ).
It turns out this is equivalent to $QuantityOrdered != '0' || $QuantityShipped != '0'. Fill in the table, and you'll see.
This equivalence, where "NOT (a AND b)" is equivalent to "(NOT a) OR (NOT b)", is called ''De Morgan's Law''.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Hibernate 4 and Spring Data JPA not populates collection I am using Hibernate 4 and Spring Data JPA, I have a ManyToOne relationship with FetchType.EAGER, Contact has many Addresses, my problem is when I run the test I cannot get the populated collection in the Contact entity, but if I retrieve the Address entity I get access to the Contact entity.
This is Contact entitty code:
@Entity(name = "CONTACT")
public class ContactJPA {
    @OneToMany(mappedBy = "contact", fetch = FetchType.EAGER, cascade = CascadeType.ALL)
    private Collection<AddressJPA> addresses;
//getters an setters
}

This is Address entity code:
@Entity(name = "ADDRESS")
public class AddressJPA {
    @ManyToOne(optional=false)
    @JoinColumn(name="CONTACT_ID", referencedColumnName = "CONTACT_ID", nullable = false)
    private ContactJPA contact;
//getters an setters
}

To retrieve and save entities I am using CrudRepository from spring framework.
This is my junit:
RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(classes = { JPAConfigurationTest.class })
@Transactional
@TransactionConfiguration(defaultRollback = true)
public class ContactRepositoryIntegrationTest {

    @Autowired
    ContactRepository contactRepository;
    @Autowired
    AddressRepository addressRepository;

    AddressJPA addressJPA;
    Integer key = 1;

    @Before
    public void setUp(){
        addressJPA = new AddressJPA();
        addressJPA = new AddressJPA();
        addressJPA.setAddressId(new Integer(1));
        addressJPA.setCountry("Argentina");
        addressJPA.setCity("Cordoba");
        addressJPA.setStreet("San Juan");
    }

    @Test
    public void thatRetrieveContactShouldPopulateAddress(){
        ContactJPA contact = new ContactJPA();
        contact.setContactId(key);
        contact.setEmail("test@email.com");
        contact = contactRepository.save(contact);

        addressJPA.setContactJPA(contact);
        addressRepository.save(addressJPA);

        AddressJPA retrievedAddress = addressRepository.findByAddressId(1);
        System.out.println("Address " + retrievedAddress);
        ContactJPA retrievedContact = contactRepository.findByContactId(key);

        System.out.println(retrievedContact.toString());
        assertNotNull(retrievedContact);
        assertEquals(key, retrievedContact.getContactId());
        assertEquals(1, contact.getAddresses().size());//this throws null pointer exception
        Iterator<AddressJPA> it = contact.getAddresses().iterator();
        assertEquals(addressJPA, it.next());
    }
}

Any suggestion?
Thanks in advance

A: Everything looks fancy, but you did not set your address to your contact. In other words, you are using your relationship only from one side (from ADDRESS side). Usually before you persist your contact, you should set address to your contact. Doing this, you have a FK column to your Contact which points to concrete address's PK_ID in address table. Likely that your Contact did not see your Address at all, because you did not make reference to it. What you need to do is set address object to your contact through setter method and it will be ok for now.


text:
Q: PHP syntax for arrays: different behaviour between PHP versions I made a PHP page with an array using the following syntax:
$Legenda = [
    "Cores"      => ["#FF0000", "#FFA500", "#FFFF00", "#64FF00", "#00AA00", "#005500", "#0000FF"],
    "ValMinimos" => [50,         62.85714,  75.71429,  88.57143, 101.42857, 114.28571, 127.12286],
    "ValMaximos" => [62.85714,   75.71429,  88.57143, 101.42857, 114.28571, 127.12286, 140]
];

which works fine on windows (PHP 5.4.6, installed using EasyPHP), but when I uploaded the same page to a Ubuntu Server (PHP 5.3.10, installed using apt-get from repositories), I get an error: "Parse error: syntax error, unexpected '[' in /var/www/ShapeTest_server_get_dados.php on line 13". Line 13 is the $Legenda array definition.
It's been a while since I programmed with PHP, but as I remember that syntax was valid. Is this an option turned off by default on linux, or why doesn't this work?

A: The shortened array syntax was only added in PHP 5.4: Arrays

As of PHP 5.4 you can also use the short array syntax, which replaces array() with [].

<?php
$array = array(
    "foo" => "bar",
    "bar" => "foo",
);

// as of PHP 5.4
$array = [
    "foo" => "bar",
    "bar" => "foo",
];
?>

Live result


text:
Q: How to enable Adaptive Application controls in Azure using Terraform I have the following recommendation from Microsoft Defender for Cloud

Adaptive application controls for defining safe applications should be enabled on your machines

I did go through the article - https://charbelnemnom.com/enable-adaptive-application-controls-in-azure-security-center and understood.
I want to enable this through Terraform rather than manually. I'm not sure where to begin.

A: There is another approach to enable Adaptive Application Control (AAC) for Azure VM's using Azure built in Policy.
Adaptive Application Control (AAC) is a feature of Azure Policy that allows you to control which applications are allowed to run on Azure Virtual Machines. Enabling AAC requires creating and assigning a default policy definition for the feature. like below.
Azure Portal > Policy > Definitions.

ARM Template.
{
"properties": {
"displayName": "Adaptive application controls for defining safe applications should be enabled on your machines",

"policyType": "BuiltIn",

"mode": "All",

    "metadata": {
    "version": "3.0.0",
    "category": "Security Center"
    },
    "parameters": {
    "effect": {
    "type": "String",
    "metadata": {
    "displayName": "Effect",
    "description": "Enable or disable the execution of the policy"
    },
    "allowedValues": [
    "AuditIfNotExists",
    "Disabled"
    ],
    "defaultValue": "AuditIfNotExists"
    }
    },
    "policyRule": {
    "if": {
    "field": "type",
    "in": [
    "Microsoft.Compute/virtualMachines",
    "Microsoft.ClassicCompute/virtualMachines"
    ]
    },
    "then": {
    "effect": "[parameters('effect')]",
    "details": {

    "type": "Microsoft.Security/assessments",

    "name": "35f45c95-xxxx-xxxx-891f-8390d1de5828",
    "existenceCondition": {

    "field": "Microsoft.Security/assessments/status.code",

    "in": [
        "NotApplicable",
    "Healthy"
    ]
    }
    }
    }
    }
    },
    "id": "/providers/Microsoft.Authorization/policyDefinitions/47a6b606-51aa-xxxxxxxxx-64b11cf66adc",
    "type": "Microsoft.Authorization/policyDefinitions",
    "name": "47a6b606-xxxx-xxx-8bb7-64b11cf66adc"
    }

Assign the policy to scope level, like below.

Assign the built in Azure Policy by using Terraform. Like below.
provider "azurerm" {
    features {}
  }

  terraform {
  required_providers {
      azurerm = {
          source = "hashicorp/azurerm"
          version = ">= 2.96.0"
      }
  }
  }

You can fetch the Policy Definition ID, like below.

resource "azurerm_subscription_policy_assignment" "auditvms" {
  name = "Adaptive application controls for defining safe applications should be enabled on your machines"
  subscription_id = "<Subscription_ID>"
  policy_definition_id = "/providers/Microsoft.Authorization/policyDefinitions/06a78e20-9358-41c9-923c-fb736d382a4d"
  description = "Shows all virtual machines not using managed disks"
  display_name = "Audit VMs without managed disks assignment"
  }

Referance: Create a policy assignment to identify non-compliant resources using Terraform.


text:
Q: How can I ensure outbound traffic uses the same interface as that of inbound traffic in Linux? I have a Linux box with two interfaces: one for data and the other for management purpose. If both are on the same network, I have a route added for both interfaces.
Imagine the routing table is:
192.168.132.0 255.255.255.0 eth0
192.168.132.0 255.255.255.0 eth1 ( management interface)

The problem is that even if a connection is initiated to mgmt IP (eth1), return traffic will be on eth0.
How can I ensure that return traffic on a connection uses the same interface as that of forwardeded traffic?

A: Ideally, both the interfaces should be part of differen IP subnets, but if you are convinced that you need to go this way only, then you should use linux split access routing.
Linux split access description
Split Access example from Novell
First, create two routing tables, T1 and T2 to be used for packets sent to or from these NICs by adding the lines
252 T1
251 T2

to /etc/iproute2/rt_tables.
Next, set up the routing rules to route incoming and outgoing packets via these tables:
ip route add 10.105.16.0/24 dev eth0 src 10.105.16.100 table T1
ip route add default via 10.105.16.2 dev eth0 src 10.105.16.100 table T1
ip rule add from 10.105.16.100 table T1

ip route add 10.105.16.0/24 dev eth1 src 10.105.16.101 table T2
ip route add default via 10.105.16.2 dev eth1 src 10.105.16.101 table T2
ip rule add from 10.105.16.101 table T2


text:
Q: xrandr says that my recently created mode is an unrecognized option when trying to add it to my moniter my moniter is actually a small tv and does in fact support 1080p although currently uibuntu says that the highest i can go up to is 1360x768. created a mode named 1080p that i can see when using command "xrandr" that does in fact have the correct resolution although im not sure if im just doing some thing stupid cuz this is my first real install not on a vm.
what ive done so far:
1: cvt 1920 1080 60
2: xrandr --newmode "1080p" (I copied the modeline) produced by cvt i can now see my mode when i use xrandr
3: xrandr --addmode Screen 0 1080p
OUTPUT: xrandr: unrecognized option '1080p'

A: The problem is with your last command.

*

*Detect you monitor name with xrandr | grep " connected " | awk '{ print$1 }' and replace it for the Screen option.

*Don't use 0 - you don't need that.

So the command would look like this:
xrandr --addmode MonitorName 1080p


text:
Q: How to parse JSON object and display in the table? I am getting the company stock information from a JSON Object by accessing the web method.
The JSON object as shown below.
<StockQuotes>
         <Stock>
            <Symbol>CAT</Symbol>
            <Last>80.95</Last>
            <Date>7/20/2012</Date>
            <Time>4:01pm</Time>
            <Change>0.00</Change>
            <Open>N/A</Open>
            <High>N/A</High>
            <Low>N/A</Low>
            <Volume>0</Volume>
            <MktCap>52.807B</MktCap>
            <PreviousClose>80.95</PreviousClose>
            <PercentageChange>0.00%</PercentageChange>
            <AnnRange>67.54 - 116.95</AnnRange>
            <Earns>7.932</Earns>
            <P-E>10.21</P-E>
            <Name>Caterpillar</Name>
        </Stock>
    </StockQuotes>

How would I parse the above mentioned JSON Object to display data in the table as shown in the below?
Symbol:CAT
Last: 80.95
Date: 7-20-2012
Time: 4:01PM
Change:0.00

A: Use an XML parser, not a regex! There are many availble for every language.
If the string had always the same format, you could also use string methods.

A: You can use XPath to extract text from specific nodes. The following are the Xpath expressions required to extract the details you want
/StockQuotes/Stock[1]/Symbol[1]
/StockQuotes/Stock[1]/Last[1]
/StockQuotes/Stock[1]/Date[1]
/StockQuotes/Stock[1]/Time[1]
/StockQuotes/Stock[1]/Change[1]

Note: IE5 and later has implemented that [0] should be the first node, but according to the W3C standard it should have been [1]!!


text:
Q: How to add skip button to ASP.NET Wizard? I know how can I skip steps programmatically but I need "Skip" button too.

A: If you wish to add a new button to the wizard control then you will need to replace the existing Templates by creating custom

*

*WizardStepNavigationTemplates(this is the template which is responsible for the controls which are displayed when on any normal wizard step)

*WizardStartNavigationTemplate(this is the template which is responsible for the controls which are displayed when on the FIRST step of the wizard) and

*WizardFinishNavigationTemplate (this is the template which is responsible for the controls which are displayed when on the Last step of the wizard)
internal class CustomWizardStartNavigationTemplate : CustomWizardNavigationTemplateBase
    {
        #region ITemplate Members
    public CustomWizardStartNavigationTemplate(WizardDisplayConfig wizardDisplayConfig):base(wizardDisplayConfig){ }

/// <summary>
/// this overrides the method to define the navigation controls which will appear in the template.
/// Literal control is used to put spacing between the controls.
/// </summary>
public override void InstantiateIn(Control container)
{
    Literal spacingliteral = new Literal();
    spacingliteral.Text += " ";
    Button btnSkip = new Button();
    Button btnSave= new Button();
    Button btnNext= new Button();

     container.Controls.Add(btnSave);
    container.Controls.Add(spacingliteral);
    container.Controls.Add(btnNext);
    container.Controls.Add(spacingliteral);
    container.Controls.Add(btnSkip);

}
#endregion

}

Something like below is a sample implementation of how you can achieve the desired results. Note that by creating these new templates you will need to add button click events etc which i have not shown in my example. This is so when user clicks the button they will be moved to the next step etc.Hope this helps.
cheers
Niall


text:
Q: Firebase write query is lagging animation I make the following firebase query but for some reason it lags my app.
const prefRef = firebase.firestore().collection('lobby').doc(lobbyNumber).collection('person').doc(docId)

prefRef.update({
            [restid]: sentiment
 })

Is there a way to make a write firebase query in the background without severely lagging the app?


text:
Q: How to load tensorflow dataset? I am trying to follow the Tensorflow text classification example Here. I want to save the tokenized dataset by using tf.data.experimental.save(). However, I can't load it properly. What should I do to load it properly? The offical Colab link is Here.

A: Split the batch labelled dataset as 2 pieces

*

*Training Dataset

*Training Dataset Label

and fit with model.fit(x=training_dataset, y=training_dataset_label)


text:
Q: How do I find out the position of a char I've got an String ("Dinosaur") and I don't exactly know how, but how do I get the position of the char "o" and is it in all possible to get two positions like if my String was ("Pool")

A: As for your first question, you can use String#indexOf(int) to get the index of every 'o' in your string.
int oPos = yourString.indexOf('o');

As for your second question, it is possible to get all positions of a given char by making a method which uses String.indexOf(int, int), tracking the previous index so that you don't repeat searched portions of the string.  You could store the positions in an array or list.

A: Use indexOf with a loop:
String s = "Pool";
int idx = s.indexOf('o');
while (idx > -1) {
  System.out.println(idx);
  idx = s.indexOf('o', idx + 1);
}

A: Simply:
public static int[] getPositions(String word, char letter)
{
    List<Integer> positions = new ArrayList<Integer>();
    for(int i = 0; i < word.length(); i++) if(word.charAt(i) == letter) positions.add(i);

    int[] result = new int[positions.size()];
    for(int i = 0; i < positions.size(); i++) result[i] = positions.get(i);

    return result;
}

A: This is probably going a little over board, but hey ;)
String master = "Pool";
String find = "o";

Pattern pattern = Pattern.compile(find);
Matcher matcher = pattern.matcher(master);

String match = null;

List<Integer[]> lstMatches = new ArrayList<Integer[]>(5);
while (matcher.find()) {

    int startIndex = matcher.start();
    int endIndex = matcher.end();

    lstMatches.add(new Integer[] {startIndex, endIndex});

}

for (Integer[] indicies : lstMatches) {

    System.out.println("Found " + find + " @ " + indicies[0]);

}

Gives me
Found o @ 1
Found o @ 2

The great thing is, you could also find "oo" as well

A: Have you tried converting the String to a char array?
int counter = 0;
String input = "Pool";
for(char ch : input.toCharArray()) {
    if(ch == 'o') {
        System.out.println(counter);
    }
    counter += 1;
}

A: Try this
 String s= "aloooha";
 char array[] = s.toCharArray();
 Stack stack = new Stack();

 for (int i = 0; i < array.length; i++) {
    if(array[i] == 'o'){
      stack.push(i);
    }
 }
 for (int i = 0; i < stack.size(); i++) {
    System.out.println(stack.get(i));
 }


text:
Q: elements of unordered list in the same line I have unordered list like following

element one

element two

I want e1 and e2 to appear in the same line. And I don't want to use display:inline-block or inline
Is it possible and how?

A: Your main alternative other than some tricky positioning is to use floats (and float clearing)
ul {
  overflow: hidden;
}

ul li {
  float: left;
}

Comes with it's own annoying problems, but there it is.
It is not necessary to set a width unless you used display: block on those lis.  Which you might have since you said you didn't want to inline them (which they are by default).
Of course there are many other list styles to consider like margin, padding, and the list-style* ones.

A: You can try setting the width and float the list left.
ul li{
 width: 100px;
 float: left;
}

JSFiddle

A:

ul {
    list-style-type: none;
    margin: 0;
    padding: 0;
}
#e1 {
    position: absolute;
    top: 0;
}
#e2 {
    position: absolute;
    top: 0;
    left: 100px;
}

element one

element two


text:
Q: Java 8: assigning a value from a stream to a variable? I just started to learn streams in java8. I am trying to convert a basic for each loop into a stream that does the exact same thing. I have checked around here and found this:
Convert For-Loop into Java stream. The issue with this is that the example collects the results at the end and I don't think I need to collect anything but to assign the value which is not explained.
the loop which I want to convert is this. As you can see I want to assign the value to the vanTire.
VanTire vanTire = null;

        for (Object tire : tireList) {
            if (tire instanceof VanTire) {
                vanTire = (VanTire) tire;
            }
        }

What I have so far with streams is this. How do I assign the value to the vanTire variable since filtering and casting is already done?
tireList.stream()
    .filter(VanTire.class::isInstance)
    .map(VanTire.class::cast)

A: After getting the correct items, you need to use .findFirst or .findAny to get an element, along with orElse to provide a default value
VanTire vanTire = (VanTire) tireList.stream().filter(VanTire.class::isInstance)
                                    .findAny().orElse(null);

*

*.elseGet and .elseThrow in Optional documentation

*.findFirst or .findAny inStream documentation

A: In general, Streams should be stateless. This is due to the fact that the elements in Streams might be processed out of order. Thus, I would suggest a solution that does not assing the value from within the Stream, but rather yield a result from the stream that is assignable to the desired type:
VanTire vanTire = tireList.stream()
    .filter(VanTire.class::isInstance)
    .findAny()
    .map(VanTire.class::cast)
    .orElse(null);

I used .orElse(null) since this maps to the semantics of the sample code provided wrt. the behaviour when tireList is empty. Depending on the business case, however, continuing computation with an Optional or calling orElseThrow(...) might be a better option.


text:
Q: Glype Proxy preg replace source Pleas help me with this Glype proxy source code. I want to make a new proxy script but I have some big issue.
When I access the website I get the styles and javascript src like this:
src="/images/"

And I want to change it with preg_replace or str_replace with src="http://example.com/images/"
I have tried this options:
$input = str_replace(PHP_EOL, '', $input);
    $input = preg_replace("/\r|\n/", "", $input);
    $input = str_replace('href="/images/', 'href="http://example.com/images/', $input);

but nothing change is still show me the website without styles.


text:
Q: Epplus Drawings with Negative Position Values I'm opening an excel file using EPPlus and the problem is that when I open the file, several ExcelDrawing in WorkSheet.Drawings have their "To" proprety with its values negative.
To.Column = -2147483648
To.ColumnOff = -2147483648
To.Row = -2147483648
To.RowOff = -2147483648

Anyone knows how can I fix this issue?
Code :
using (ExcelPackage pack = new ExcelPackage(new FileInfo(@"C:\Files\test.xlsm")))
{
   foreach (ExcelWorksheet ws in pack.Workbook.Worksheets)
   {
       foreach (ExcelDrawing drw in ws.Drawings)
       {
           if (drw.To.Column > ExcelPackage.MaxColumns || drw.To.Column < 1)
           {

               Console.WriteLine(ws.Name + "|" + drw.Name);
           }
      }
   }
   pack.Save();
}


text:
Q: create pdf of a div CSS How can I save a pdf of a div, for example :
<button>pdf</button>

some data

onclick of button I want to save this div as a pdf document.
Edit : is it possible using only CSS?

A: You need PHP export HTML to PDF:
http://pdfcrowd.com/i/php-export-html-to-pdf.html check this link.
Alternatively you can use this: http://www.phpclasses.org/package/6638-PHP-Generate-a-PDF-file-with-a-listing-of-data-records.html
I hope this will help you!
PS: you haden't offered us more info, code you tried etc.


text:
Q: Watch points on memory address With the new change from gdb to lldb , I can't find a way how to set watch points on some memory addresses .
In gdb I used this
watch -location *0x123456

Doing the same in lldb
w s e *0x123456

Isn't working for me .
So what can I use to run the same command in lldb ?

A: Omit the "dereferencing operator" * when setting the watch point in lldb, just pass the address:
watchpoint set expression -- 0x123456
# short form:
w s e -- 0x123456

sets a watchpoint at the memory location 0x123456. Optionally you can set the number of bytes to watch with --size. Example in short form:
w s e -s 2 -- 0x123456

You can also set a watchpoint on a variable:
watchpoint set variable <variable>
# short form:
w s v <variable>

Example: With the following code and a breakpoint set at the second line:
int x = 2;
x = 5;

I did this in the Xcode debugger console:

(lldb) p &x
(int *) $0 = 0xbfffcbd8
(lldb) w s e -- 0xbfffcbd8
Watchpoint created: Watchpoint 1: addr = 0xbfffcbd8 size = 4 state = enabled type = w
    new value: 2
(lldb) n

Watchpoint 1 hit:
old value: 2
new value: 5
(lldb)

More simply, I could have set the watchpoint with

(lldb) w s v x
Watchpoint created: Watchpoint 1: addr = 0x7fff5fbff7dc size = 4 state = enabled type = w
    declare @ '/Users/martin/Documents/tmpprojects/watcher/watcher/main.c:16'
    watchpoint spec = 'x'


text:
Q: Nested transactions are not allowed in Android studio I am working on an android app and I am using realm DB, my app was worked properly, but suddenly if i want to write to DB the app stopped and give me this error.
Getting MAX_TEXTURE_SIZE from GradienCache
Getting MAX_TEXTURE_SIZE from Caches::initConstraints()
---
FATAL EXCEPTION: main
java.lang.IllegalStateException: Nested transactions are not allowed. Use
commitTransaction() after each beginTransaction().
atio.realm.internal.ImplicitTransaction.promoteToWrite(ImplicitTransaction.java:)
 at io.realm.Realm.beginTransaction(Realm.java:1454)
at.onClick(AddMedication.java:52)
   at android.view.View.performClick(View.java:4240)
 at android.view.View$PerformClick.run(View.java:17721)
      at android.os.Handler.handleCallback(Handler.java:730)
            at android.os.Handler.dispatchMessage(Handler.java:92)
              at android.os.Looper.loop(Looper.java:137)
             at android.app.ActivityThread.main(ActivityThread.java:5103)
            at java.lang.reflect.Method.invokeNative(Native Method)
           at java.lang.reflect.Method.invoke(Method.java:525)
      at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:737)
      at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:553)
   at dalvik.system.NativeStart.main(Native Method)
Could not find class 'android.util.ArrayMap', referenced from method
com.android.tools.fd.runtime.MonkeyPatcher.monkeyPatchExistingResources

I tried many available solutions but the problem have not fixed yet!
any help!

A: Probably you are calling beginTransaction() twice. Before the second call you must commit or rollback the first one.
beginTransaction(); // First call
try{
  doSomeWorkOnDB();
  commit();
} except (...){
  rollback();
}
...
beginTransaction(); // Second call
try{
  doOtherWorkOnDB();
  commit();
} except (...){
  rollback();
}

Hope it helps.


text:
Q: How to calculate area using QgsDistanceArea? I am trying the following code as given in the QGIS documentation:
d = QgsDistanceArea()
d.setProjectionsEnabled(True)

print "distance in meters: ", d.measureLine(QgsPoint(10,10),QgsPoint(11,11))

But getting the following error:

" AttributeError: 'QgsDistanceArea' object has no attribute 'setProjectionsEnabled' "

What is wrong here?

A: I think a similar problem was asked here where it is mentioned that the cookbook should be updated.  From the link given, you should replace setProjectionsEnabled with setEllipsoidalMode.


text:
Q: What is the structure of ATIS (Airline Travel Information System) dataset When I use ATIS (Airline Travel Information System) dataset(http://lisaweb.iro.umontreal.ca/transfert/lisa/users/mesnilgr/atis/) to do research in recurrent-neural-network. I am confused with it's structure.
For example, after using data = pickle.load(open("./dataset/atis.fold0.pkl",  "rb"),encoding='iso-8859-1') to load the atis.fold0.pkl, I use print (np.shape(data_train)) to get (4,). I think the data[0] is the training set, the data[1] is the valid set, the data[2] is the test set and the data[3] is the dict.
But when I use print(np.shape(data[0])), I get (3, 3983). I wonder why I get 3 rows in it? what's the difference between these three rows.
And what's the difference between file atis.fold0.pkl, atis.fold1.pkl, atis.fold2.pkl, atis.fold3.pkl, atis.fold4.pkl?

A: f = gzip.open(filename, 'rb')
try:
    train_set, valid_set, test_set, dicts = pickle.load(f, encoding='latin1')
except:
    train_set, valid_set, test_set, dicts = pickle.load(f)

print np.shape(train_set)

Each of the pickle can be divided into training, validation, testing, and its dictionary. When you see the dictionary elements, they contain the words2idx
tables2idx
labels2idx
Now test the following code

for i in train_set:
	print len(i[0])

It will return same length file.
So the First element is the words.Second is the tables2idx and third is final result of slot filling (labels2idx)
Use the dict to decry pt the ids, you will get the meaning.


text:
Q: Prove that the curves of the family $v^3/u^2=k$ are geodesics on a surface Prove that the curves of the family $v^3/u^2=k$ where $k$ is a constant are geodesics on a surface with the metric
$$v^2 \, du^2-2uv \, du+2u^2 \, dv^2$$ where $u,v \gt 0$.

A: if you want to prove a curve is geodesic, you can use the following equivalent condition :
$(r^{'},r^{''},n)=0$
your curve equation is :
$r(u,v)=v^{3}-ku^{2}=0$
since, $(r^{'},r^{''},n)=(r^{'}\times{r^{''}})\cdot{n}=\vert{r^{'}}\vert\cdot\vert{r^{''}}\vert\sin\theta{\cdot{n}}$
therefore, $sin\theta=0$$\Longrightarrow{cos\theta}=1$$\Longrightarrow$$\frac{r^{'}\cdot{r^{''}}}{\vert{r^{'}}\vert\vert{r^{''}}\vert}=1$
in which, $r^{'}=(-2ku,3v^{2})$  $r^{''}=(-2k,6v)$


text:
Q: Hiding a django website while development I developed a django website on my local machine and now is the time to upload it on a server. I would like that during the time i work on it, only logged in users can see it.
I thought about a
{% if is_logged_in %}
{% else %}
{% endif %}

structure in my base.py template but not all my views return a Context so it doesn't always work.
Is there any simple way without having to change much of code to hide every pages?

A: Use django.contrib.auth.decorators.login_required. It is a decorator, that will prevent users from viewing anything, if they are not logged in. Or you can find middleware for this: http://djangosnippets.org/snippets/1179/.
Middleware will be better, becuase it is unobtrusive and you can remove it later.

A: There are 2 reasonable solutions for this.

*

*Using a middleware to demand authentication (if needed I can put an example online, but the code should be trivial)

*Using authentication in your webservers. That way you can simply add a couple of IP addresses and/or users to have access. These days it's pretty easy to link your http authentication to Django aswell so with both mod_wsgi and mod_python you can let Apache authenticate it's users via Django.

A: Another reasonable way to do this would be to client certificates. That way you can also test the parts that don't require you to be logged in

A: or protect the whole directory on the server with .htaccess and this also prevents google finding the site in development.


text:
Q: Which BT stack does Tizen support? I would like to know if Tizen has support for BT and if so does it use the open source bluez protocol?
Also I would like to know where to start digging when it comes to bluetooth in Tizen.
Thanks in advance!

A: Packages in tizen have bluez, checked in package list
https://www.tizen.org/package-list
Not sure about the version or other info

A: Yes, it supports Bluetooth and it uses bluez stack and obexd.
Version: Bluez-4.101, Obexd-0.34
The profiles supported by Tizen Bluetooth are GAP, SDP, A2DP, AVRCP, HFP, HSP, GATT.
Obexd profiles include OPP, FTP, PBAP, SYNC, MAP

A: On SamsungGear2 :
~/tizen-sdk/tools/sdb shell rpm -qa | grep bluez
bluez-4.101_40-8.1.rinatoxx.armv7l

I can also test on SamsungZ1 or tizen camera if needed


text:
Q: Using Graphite, how can I display a series of charts that all share the same yMax? Graphite has a render API that allows an app to request a chart, with specific attributes: colors, legend or not, title, data on the chart, and so on.  One thing that can be varied is the y-axis limits (yMin and yMax).
I'd like to display 4 charts, all with the same data, but over different time intervals. I want the yaxis to be the same on each of the 4 charts.  If I don't specify the yMax, then the yMax gets chosen automatically by Graphite, and it gets chosen to a different value for each chart:

You can see the ymax ranges from 300 to 400.  It makes the charts hard to compare. What I want is this:

I can explicitly set the yMax, but ... how do I choose the right value?  The only way I can see to do this now is to query all the raw data, then compute the yMax, then actually use the computed yMax in the render UI.
This works but querying the raw data is REALLY EXPENSIVE and ships a ton of json.  Has anyone figured out a way to avoid this?  Suggestions?

A: The way I did it was the way I described:
query the raw data, compute the max, then in a callback, request charts with yMax set to that value.


text:
Q: Failing first name and last name regex test I am having quite a weird error in my rails' unit test.
I have the following test which fails for some reason:
should_not allow_value('@!>::<>').for(:first_name)

and the following validation in my model:
validates_format_of :first_name, :last_name, with: (/[\w]*/), allow_blank: true

Any ideas as to why the test fails?
PS: Error seems to go away when I change the * to a + in the regex...But why!

A: The regex /[\w]*/ matches zero or more word characters in the input. Since there are no word characters in your test string, it happily validates it. /[\w]+/ needs at least one word character to have a match, and that's why it works with your test string.
I think you should use /^[\w]*$/ to specify that from the start of your string to the end, you only want word characters (special characters ^ and $ match the start and the end of input, respectively, in a regex). Note that this allows a blank input.


text:
Q: An integral with a fractional part in 3 dimensions The evaluation with Maple suggests the triple integral is around $1$, but Mathematica tells
it's $0.0958758$. When using the code
N[Integrate[FractionalPart[x/y] FractionalPart[y/z] FractionalPart[z/x], {x, 0, 1}, {y, 0, 1}, {z, 0, 1}]]

it returns:
"NIntegrate::slwcon: Numerical integration converging too slowly; suspect one of the following: singularity, value of the integration is 0, highly oscillatory integrand, or WorkingPrecision too small. >>
NIntegrate::eincr: The global error of the strategy GlobalAdaptive has increased more than 2000 times. The global error is expected to decrease monotonically after a number of integrand evaluations. Suspect one of the following: the working precision is insufficient for the specified precision goal; the integrand is highly oscillatory or it is not a (piecewise) smooth function; or the true value of the integral is 0. Increasing the value of the GlobalAdaptive option MaxErrorIncreases might lead to a convergent numerical integration. NIntegrate obtained 0.09587582633950331and 0.004696948831748114 for the integral and error estimates. >>"
I'd like to know if Mathematica's approximation is correct, and if there is a possible closed form.

A: The Maple image you showed in your comment above was done in Maple 2D math (document mode). little hard to replicate it using classical interface (worksheet mode) which I use since one does not see the actual Maple commands that way.
The Maple commands you ave also might be using another package that was loaded before and not shown, such as Maple's Student. It is best that you post complete self contained Maple code to be able to compare.
But I have Maple 17, and not able to get the same result. Maple is not able to do this integral either.
restart:
f:=x->x-floor(x);
Int(f(x/y)*f(y/z)*f(z/x),[x=0..1,y=0..1,z=0..1]);
value(%);

Error, (in floor) too many levels of recursion

There is one thing I noticed though, is that Maple has a rule to integrate floor function, and Mathematica does not do it: Maple's definition is same as M:

floor - greatest integer less than or equal to a number

hence
restart:
int(floor(x),x);

    (*  floor(x)*x  *)

and in Mathematica, it remains unevaluated
Integrate[Floor[x], x]

But do you want to see something bizarre? I gave Integrate a rule integrate floor(x/y) to x*floor(x/y), which is also how it is defined in Maple:
 int(floor(x/y),x);
 (*  floor(x/y)*x *)

Unprotect Integrate and add the rule:
 (Unprotect[Integrate]; Integrate[Floor[x_/y_],x_] := x Floor[x/y];Protect[Integrate];)
 Integrate[x-Floor[x/y] , {x, 0, 1}]

and this is the result

Where did the 99999999999999999999/(100000000000000000000 y) come from? This should be 1
 N[%]

Very strange result. Here is Maple's result:
 int(x-floor(x/y),x=0..1);
 (* -floor(1/y)+1/2 *)

So same final result, but M exact answer has this 99999999999999999999/(100000000000000000000 y) term which only becomes 1.0 with using N on it. This might be related to the WorkingPrecision messages you are seeing.
The bottom line is: Maple does not give 1 as you showed in your screen image.

A: The analytic answer is
$$
%\sum_{n=1}^\infty \frac{1}{2n(n+1)^2}\sum_{n=1}^\infty \frac{1+3n}{6n^2(n+1)^3}+\sum_{n=1}^\infty \frac{3n^2-1}{6n^2(n+1)^3}=\\
1+\pi ^2\frac{2 \zeta (3)-9}{72} \approx 0.0958502
$$
Therefore, Mathematica is correct.
Proof
The 3D integral
NIntegrate[FractionalPart[x/y] FractionalPart[y/z] FractionalPart[z/x],
   {x, 0, 1}, {y, 0, 1}, {z, 0, 1}]

0.0958741

depends only on ratios between x, y, and z. Therefore, it can be reduced to the 2D integral
NIntegrate[FractionalPart[x/y] y FractionalPart[1/x], {x, 0, 1}, {y, 0, 1}]

0.0958383

It has the following structure
ArrayPlot@Table[FractionalPart[x/y] y FractionalPart[1/x],
    {x, 0.001, 1, 0.001}, {y, 0.001, 1, 0.001}]

We can split the integral to two parts
NIntegrate[FractionalPart[x/y] y FractionalPart[1/x], {x, 0, 1}, {y, 0, x}]
NIntegrate[FractionalPart[x/y] y FractionalPart[1/x], {x, 0, 1}, {y, x, 1}]

0.0176263
0.0782212

After substitution $y/x = ξ$ the first one becomes
NIntegrate[x FractionalPart[1/x], {x, 0, 1}] NIntegrate[x^2 FractionalPart[1/x], {x, 0, 1}]

0.0176233

The second one is equivalent to
NIntegrate[x (1 - x) FractionalPart[1/x], {x, 0, 1}]

0.0781823

These integrals can be written as a sum of
Integrate[x (1/x - n), {x, 1/(n + 1), 1/n}] // Simplify
Integrate[x^2 (1/x - n), {x, 1/(n + 1), 1/n}] // Simplify
Integrate[x (1 - x) (1/x - n), {x, 1/(n + 1), 1/n}] // Simplify

1/(2 n (1 + n)^2)
(1 + 3 n)/(6 n^2 (1 + n)^3)
(-1 + 3 n^2)/(6 n^2 (1 + n)^3)

Sum[1/(2 n (1 + n)^2), {n, 1, ∞}]
Sum[(1 + 3 n)/(6 n^2 (1 + n)^3), {n, 1, ∞}]
Sum[(3 n^2 - 1)/(6 n^2 (1 + n)^3), {n, 1, ∞}]

1/2 (2 - π^2/6)
1/6 (3 - 2 Zeta[3])
1/12 (6 - π^2 + 4 Zeta[3])

Finally, we obtain
1/2 (2 - π^2/6) 1/6 (3 - 2 Zeta[3]) + 1/12 (6 - π^2 + 4 Zeta[3]) // Simplify
N[%]

1 + 1/72 π^2 (-9 + 2 Zeta[3])
0.0958502


text:
Q: Is there anyway to optimize `SHOW DATABASES` query in MYSQL The following is logged multiple times in MYSQL_SLOW_QUERIES:
Mon Nov 25 07:18:57 2013
 Query_time: 1.467255  Lock_time: 0.000132 Rows_sent: 9  Rows_examined: 9
SET timestamp=1385389137;
SHOW DATABASES
I am guessing that query was run when I was using the phpMyAdmin. Is it an issue with the server or there is something I need to do to fix it?

A: SHOW DATABASES an sich should not be slow. It can be a bit slower the first time you run the command, when it needs to read the info. It can be slower after a long time, when the info has left the cache.
There are a number of known bugs in MySQL which can cause this, though. Updating your system to the latest stable build will fix this. What version are you currently using?

A: phpMyAdmin 4.1.0-rc1 (available now) hopefully no longer uses SHOW DATABASES; please give it a try.


text:
Q: Data Purging in SQL Server Table I have the a Requirement where I have to Delete in batches in sql server , and also track the number of count affected in the end. My Sample Code is as Follows:
Declare @count int
Declare @deletecount int

set @count=0

While(1=1)
BEGIN

BEGIN TRY

BEGIN TRAN
DELETE TOP 1000 FROM --CONDITION

SET @COUNT = @COUNT+@@ROWCOUNT

IF (@@ROWCOUNT)=0
Break;

COMMIT

END CATCH

BEGIN CATCH

ROLLBACK;
END CATCH

END

set @deletecount=@COUNT

Above Code Works fine, but how to keep track of @deletecount if Rollback happens in one of the batch.

A: Some potential issues with the code :

*

*while loop never exits/breaks

declare @tbl table(foo bit); --deleting from an empty table
declare @COUNT int;
declare @iteration int = 0;

While(1=1)
BEGIN
    --loop safety net
    if @iteration >= 100
    begin
        break --exit after 100 iterations
    end
    select @iteration = @iteration+1

    BEGIN TRY

        DELETE TOP (1000) FROM @tbl; --@tbl is empty

        SET @COUNT = @COUNT+@@ROWCOUNT;-- <-- this always sets @@rowcount = 1

        IF (@@ROWCOUNT)=0 -- ... so this can never be 0 --> will never exit the loop
        Break;

    END TRY
    BEGIN CATCH
    END CATCH

END --end while

select @iteration as iterations;

*Open transaction at the end of the batch

declare @tbl table(foo bit); --<-- empty table
declare @COUNT int;
declare @myrowcount int;
declare @iteration int = 0;

While(1=1)
BEGIN
    --loop safety net
    if @iteration >= 100
    begin
        break --exit after 100 iterations
    end
    select @iteration = @iteration+1

    BEGIN TRY
        BEGIN TRAN --<-- transaction begins on each iteration

        DELETE TOP (1000) FROM @tbl; --@tbl is empty

        set @myrowcount = @@rowcount;

        SET @COUNT = @COUNT+@myrowcount;

        IF (@myrowcount)=0
        Break; --<-- if this breaks... transaction is neither committed nor rolledback

        COMMIT --<-- commited on each iteration, when no error
    END TRY
    BEGIN CATCH
        ROLLBACK --<-- or rolled back on each iteration error
    END CATCH

END --end while

select @iteration as iterations, @@trancount as open_transactions;

rollback transaction;

*loop keeps trying to delete the same erroneous batch (over and over again) and never exits

create table parent (id int primary key clustered);
create table child (parentid int references parent(id));
go

--some parents
insert into parent(id)
select top (200) row_number() over(order by @@spid)
from sys.all_objects;
--and a child
insert into child(parentid) values (75)
go

declare @COUNT int;
declare @myrowcount int;
declare @errormsg nvarchar(max);
declare @iteration int = 0;

While(1=1)
BEGIN
    --loop safety net
    if @iteration >= 100
    begin
        break --exit after 100 iterations
    end
    select @iteration = @iteration+1

    BEGIN TRY

        DELETE TOP (10) t --changed the batch size..for the example
        from (select top (10000) * from parent order by id) as t;
        set @myrowcount = @@rowcount;

        SET @COUNT = @COUNT+@myrowcount;

        IF (@myrowcount)=0
        Break;

    END TRY
    BEGIN CATCH
        select @errormsg = isnull(@errormsg, '') + error_message();
    END CATCH

END --end while

select @iteration as iterations, @errormsg as errormsg;

--some parents have been deleted (8th batch kept failing, there is an fk to parent 75)
select *
from parent
go
drop table child
drop table parent
go

You could rectify all the above issues...(last one, to skip erroneous batches being a bit more "difficult"), by implementing logic in the where clause (eg. exclude rows which are referenced etc) according to your model. Trying to implement a straight deletion, without any rules, and skipping failures makes it a bit harder.
Just an example: when a batch fails, after 3 attempts, take another deletion route. Since each deletion is atomic, transactions are not really needed here (besides, if the batch is called from a parent module, a plain ROLLBACK in the batch would "invalidate" any transactions opened in the parent module, before the batch execution)
create table parent (id int primary key clustered);
create table child (parentid int references parent(id));
go

--some parents
insert into parent(id)
select top (200) row_number() over(order by @@spid)
from sys.all_objects;
--and two children
insert into child(parentid) values (75), (115) --, (9), (18) --: add 9 and 18 and nothing gets deleted, alternative route in the example does not work
go

declare @COUNT int;
declare @myrowcount int;
declare @iteration int = 0;
declare @errormsg nvarchar(max);
declare @ierrorcnt int=0;

declare @deletedids table(id int);
declare @lastsuccessfullydeletedid int = 0;

select @COUNT = 0;
While(1=1)
BEGIN
    --loop safety net
    if @iteration >= 100
    begin
        break --exit after 100 iterations
    end
    select @iteration = @iteration+1

    BEGIN TRY

        --when 10 consecutive errors in a single iteration..just quit the loop
        if @ierrorcnt >= 10
        begin
            break;
        end

        BEGIN TRAN --<-- transaction begins on each iteration

        if @ierrorcnt >= 3 --when 3 consecutive errors in the iteration..try to bypass the current batch
        begin

            delete top (10) t
            output deleted.id into @deletedids(id)
            from (select top (10) * from (select top (2*10) * from parent where id > @lastsuccessfullydeletedid order by id) as a order by id desc) as t

            select @myrowcount = count(*), @lastsuccessfullydeletedid = max(id)
            from @deletedids;

            delete from @deletedids;
        end
        else
        begin
            DELETE TOP (10) FROM parent where id > @lastsuccessfullydeletedid;
            set @myrowcount = @@rowcount;
        end

        SET @COUNT = @COUNT+@myrowcount;

        COMMIT --<-- commited on each iteration, when no error

        IF (@myrowcount)=0 and @ierrorcnt = 0
        Break;

        set @ierrorcnt = 0; --everything ok, set iteration error counter to 0
    END TRY
    BEGIN CATCH
        ROLLBACK --<-- or rolled back on each iteration error
        if @ierrorcnt = 0
        begin
            select @errormsg = isnull(@errormsg, '') +';'+ error_message();
        end
        set @ierrorcnt = @ierrorcnt + 1; --error, increase the iteration error counter

    END CATCH

END --end while

select @iteration as iterations, @@trancount as open_transactions;
select @iteration as iterations, @errormsg as errormsg;

--some parents have been deleted
select * /*2 failed batches, 20 rows left*/
from parent

select @COUNT as [count/deleted] --<--this is also the deleted count

go
drop table child
drop table parent
go

..without any errors, in your original code, @count = @deletedcount
declare @tbl table(foo int); --<-- empty table
insert into @tbl(foo)
select top (100000) row_number() over(order by @@spid)
from sys.all_objects as a
cross join sys.all_objects as b;

--batch 1000, max iterations for the @tbl count
declare @maxiterations int;
select @maxiterations = 1+count(*) / 1000
from @tbl

declare @COUNT int;
declare @deletedcount int;
declare @myrowcount int;
declare @iteration int = 0;

select @COUNT = 0, @deletedcount = 0;

While(1=1)
BEGIN
    --loop safety net
    if @iteration >= @maxiterations
    begin
        break --exit after @maxiterations
    end
    select @iteration = @iteration+1;

    BEGIN TRY

        BEGIN TRAN

        DELETE TOP (1000) FROM @tbl
        where foo%5 = 0 ;

        set @myrowcount = @@rowcount;

        SET @COUNT = @COUNT+@myrowcount;
        set @deletedcount = @deletedcount + @myrowcount;

       COMMIT

        IF @myrowcount=0
        Break;

    END TRY
    BEGIN CATCH
        ROLLBACK
    END CATCH

END --end while

select @iteration as iterations, @@trancount as open_transactions;
select @count as _count, @deletedcount as deletedcount;


text:
Q: How to test react konva from cypress? I have rectangles as screens on canvas using react-konva. How to test clicking the screens rectangle on testing tools like cypress that uses DOM Element to select the target element?
I am seeing that this is impossible, unless by creating screens DOM Element for testing purpose apart of what currently exists on the canvas. Somehow this will take a lot of time and cumbersome too.
So I wonder if we have a way to work around this to test objects that are drawn inside canvas itself?

A: Take a look into Konva testing code. Like https://github.com/konvajs/konva/blob/master/test/functional/MouseEvents-test.js
You can emulate clicks with this code (from here):
Konva.Stage.prototype.simulateMouseDown = function(pos) {
  var top = this.content.getBoundingClientRect().top;

  this._mousedown({
    clientX: pos.x,
    clientY: pos.y + top,
    button: pos.button || 0
  });
};

// the use it:
stage.simulateMouseDown({ x: 10, y: 50 });

But you have to find a way to access the stage instance for such testing. And I am not sure it is good in a cypress way, because its API is abstract and DOM-based.
Or you can try to trigger events with cypress:
cy.get(`.container > div`)
        .trigger('mousedown', { clientX: x, clientY: y })


text:
Q: Is initializing a variable in between variable declarations forbidden? I have something like
integer a
integer b
b = 0
integer c

a = 0
c = 0

which does not work with the error

"A specification statement cannot appear in the executable section."

However, changing it to
integer a
integer b
integer c

a = 0
b = 0
c = 0

works.

A: Yes, this is forbidden in Fortran. This is defined in the Fortran 2008 Standard, Cl. 2.3.2 "Statement order":

1 The syntax rules of clause 2.1 specify the statement order within program units and subprograms. These rules
  are illustrated in Table 2.1 [...]. Table 2.1 shows the ordering rules for statements and applies to
  all program units, subprograms, and interface bodies. Vertical lines delineate varieties of statements that may
  be interspersed and horizontal lines delineate varieties of statements that shall not be interspersed. [...] Between USE and CONTAINS statements in a
  subprogram, nonexecutable statements generally precede executable statements [...]

(Emphasis mine)

[Slightly off-topic, but related] Please note that while
integer :: a
integer :: b = 0
integer :: c

is allowed, this has the side effect that b gets the save attribute. That is typically not what you want...

A: The error message is quite clear. Fortran programs and subprograms are divided into two parts. First the specification part where you use modules, define variables, derived types, interfaces... And then the executable part where you put the actual executable statements or control structures.
It is not possible to mix them.

A: The situation is murkier in f2008, with the BLOCK construct. That construct necessarily lies among the executable statements, but is often there for the sole purpose of adding the capability to place some specification statements after executable statements, as when an assumed length pointer is to be pointed at anonymous memory.
EDIT: Example
module anonymous
   use ISO_C_BINDING
   implicit none
   interface
      function malloc(size) bind(C,name='malloc')
         import
         implicit none
         type(C_PTR) malloc
         integer(C_SIZE_T), value :: size
      end function malloc
      subroutine free(ptr) bind(C,name='free')
         import
         implicit none
         type(C_PTR), value :: ptr
      end subroutine free
      function strlen(str) bind(C,name='strlen')
         import
         implicit none
         type(C_PTR), value :: str
         integer(C_SIZE_T) strlen
      end function strlen
   end interface
   contains
      function hello()
         type(C_PTR) hello
         character(LEN=*,KIND=C_CHAR), parameter :: world = &
            'Hello, world'//C_NULL_CHAR
         character(LEN=len(world),KIND=kind(world)), pointer :: fptr
         hello = malloc(len(world,KIND=C_SIZE_T))
         call C_F_POINTER(hello,fptr)
         fptr = world
      end function hello
end module anonymous

program test
   use anonymous
   implicit none
   type(C_PTR) cptr
   character(LEN=:,KIND=C_CHAR), pointer :: fptr
   integer(C_SIZE_T) hello_len
   cptr = hello()
   hello_len = strlen(cptr)
   BLOCK
      character(LEN=hello_len,KIND=C_CHAR), pointer :: temp
      call C_F_POINTER(cptr,temp)
      fptr => temp
   end BLOCK
   write(*,'(*(g0))') fptr(1:strlen(cptr))
end program test


text:
Q: MySQL Triggers with variable Input I am trying to create a Trigger for a table that UDATES. I thought I could do this with multiple Triggers but I guess MySQL does not support multiple triggers on one table for the same type. So I a forced to include this into one trigger.
Basically I have trying to insert a new record into a different table based on what is updated in the current table.
Here is what I have so far and it works:
BEGIN
-- Definition start
INSERT INTO prices (stationID, price, type,
prevPrice, prevDate, dateCreated, apiKey, uid)
VALUES(NEW.stationID, NEW.regPrice, 'reg', OLD.regPrice,
OLD.regDate, NEW.regDate, NEW.lastApiUsed, NEW.lastUpdatedBy);
-- Definition end
END

What I need to happen is the type may change based on what type the user gives. Since the user may only update one type at a given time. I was thinking about an IF IF THEN statement but I wasn't sure how to get it to work. I was thinking I could use a String value of the column name to use in the IF statement but I an not sure if that is possible.
Something like this:
    BEGIN
    -- Definition start
    IF(type == 'reg') THEN
    INSERT INTO prices (stationID, price, type,
    prevPrice, prevDate, dateCreated, apiKey, uid)
    VALUES(NEW.stationID, NEW.regPrice, 'reg', OLD.regPrice,
    OLD.regDate, NEW.regDate, NEW.lastApiUsed, NEW.lastUpdatedBy);
    END IF;
    -- Definition end
    END

A: I was able to use IF THEN ELSE to complete the transaction. Then I tested the condition for a NULL value. If it is TRUE I then ran my code. Now for some reason it only does one INSERT command even though the UPDATE is for more than one. Any thoughts on this?
BEGIN
-- Definition start
IF(NEW.regPrice IS NOT NULL) THEN
INSERT INTO prices (stationID, price, type,
prevPrice, prevDate, dateCreated, apiKey, uid)
VALUES(NEW.stationID, NEW.regPrice, 'reg', OLD.regPrice,
OLD.regDate, NEW.regDate, NEW.lastApiUsed, NEW.lastUpdatedBy);

ELSEIF(NEW.midPrice IS NOT NULL) THEN
INSERT INTO prices (stationID, price, type,
prevPrice, prevDate, dateCreated, apiKey, uid)
VALUES(NEW.stationID, NEW.midPrice, 'mid', OLD.midPrice,
OLD.midDate, NEW.midDate, NEW.lastApiUsed, NEW.lastUpdatedBy);

ELSEIF(NEW.prePrice IS NOT NULL) THEN
INSERT INTO prices (stationID, price, type,
prevPrice, prevDate, dateCreated, apiKey, uid)
VALUES(NEW.stationID, NEW.prePrice, 'pre', OLD.prePrice,
OLD.preDate, NEW.preDate, NEW.lastApiUsed, NEW.lastUpdatedBy);
END IF;
-- Definition end
END


text:
Q: Follow up to splitting a sheet into multiple workbooks I am trying to modify this code found here.
The code works great, but want to know how to enter column letter instead of number.
I believe it has something to do with this line
sCol = Application.InputBox(aibPrompt, aibtitle, aibDefault, , , , , 1)

but not able to get it to work.
Here is the code as found on the other page.
Option Explicit

Sub ExportToWorkbooks()

     Const aibPrompt As String = "Which column would you like to filter by?"
    Const aibtitle As String = "Filter Column"
    Const aibDefault As Long = 3

    Dim dFileExtension As String: dFileExtension = ".xlsx"
    Dim dFileFormat As XlFileFormat: dFileFormat = xlOpenXMLWorkbook
    Dim dFolderPath As String: dFolderPath = "C:\Users\WalteR01\Desktop\VPN Revalidations\Split by Manager\"

    If Right(dFolderPath, 1) <> "\" Then dFolderPath = dFolderPath & "\"
    If Len(Dir(dFolderPath, vbDirectory)) = 0 Then Exit Sub ' folder not found
    If Left(dFileExtension, 1) <> "." Then dFileExtension = "." & dFileExtension

    Application.ScreenUpdating = False

    Dim sCol As Variant
    sCol = Application.InputBox(aibPrompt, aibtitle, aibDefault, , , , , 1)
    If Len(CStr(sCol)) = 0 Then Exit Sub ' no entry
    If sCol = False Then Exit Sub ' canceled

    Dim sws As Worksheet: Set sws = ActiveSheet
    If sws.FilterMode Then sws.ShowAllData
    Dim srg As Range: Set srg = sws.Range("A1").CurrentRegion
    Dim srCount As Long: srCount = srg.Rows.Count
    If srCount < 3 Then Exit Sub ' not enough rows
    Dim srrg As Range: Set srrg = srg.Rows(1) ' to copy column widths
    Dim scrg As Range: Set scrg = srg.Columns(sCol)
    Dim scData As Variant: scData = scrg.Value

    ' Write the unique values from the 1st column to a dictionary.

    Dim dict As Object: Set dict = CreateObject("Scripting.Dictionary")
    dict.CompareMode = vbTextCompare ' case insensitive

    Dim Key As Variant
    Dim r As Long

    For r = 2 To srCount
        Key = scData(r, 1)
        If Not IsError(Key) Then ' exclude error values
            If Len(Key) > 0 Then ' exclude blanks
                dict(Key) = Empty
            End If
        End If
    Next r
    If dict.Count = 0 Then Exit Sub ' only error values and blanks
    Erase scData

    Dim dwb As Workbook
    Dim dws As Worksheet
    Dim dfcell As Range
    Dim dFilePath As String
    Dim DateText As String: DateText = Format(Date, "_mm_yyyy")

    For Each Key In dict.Keys
        ' Add a new (destination) workbook and reference the first cell.
        Set dwb = Workbooks.Add(xlWBATWorksheet) ' one worksheet
        Set dws = dwb.Worksheets(1)
        Set dfcell = dws.Range("A1")
        ' Copy/Paste
        srrg.Copy
        dfcell.PasteSpecial xlPasteColumnWidths
        srg.AutoFilter sCol, Key
        srg.SpecialCells(xlCellTypeVisible).Copy dfcell
        sws.ShowAllData
        dfcell.Select
        ' Save/Close
        dFilePath = dFolderPath & Key & DateText & dFileExtension  ' build the file path
        Application.DisplayAlerts = False ' overwrite without confirmation
        dwb.SaveAs dFilePath, xlOpenXMLWorkbook
        Application.DisplayAlerts = True
        dwb.Close SaveChanges:=False
    Next Key

    sws.AutoFilterMode = False
    Application.ScreenUpdating = True

    MsgBox "Data exported.", vbInformation

End Sub

I have tried to change the line as stated but no luck. The application inbox is what I need to update but not sure how. This is the page I have been using https://learn.microsoft.com/en-us/office/vba/api/excel.application.inputbox

A: Dim sCol As Variant
sCol = Application.InputBox(aibPrompt, aibtitle, aibDefault, , , , , 1)

As documented here: https://learn.microsoft.com/en-us/office/vba/api/excel.application.inputbox#:~:text=The%20following%20table%20lists%20the%20values%20that%20can%20be%20passed%20in%20the%20Type%20argument
The last argument controls what type of value(s) can be accepted by the InputBox: 1 = Numeric so you need to swap that out for 2 (Text)
sCol = Application.InputBox(aibPrompt, aibtitle, aibDefault, , , , , 2)

OK now I read down...  When you call srg.AutoFilter sCol, Key the first argument to AutoFilter should be the column number in the range to be filtered to which the filter should be applied.
Note if your table doesn't start in ColA there needs to be some adjustment, but if it does you could use Cells(1, sCol).Column to convert your column letter, so try:
srg.AutoFilter sws.Cells(1, sCol).Column, Key


text:
Q: SP Search -- Exclude author Is it possible to exclude the Author details to be returned by Search API
The managed property is not editable
Thanks in advance

A: This was resolved by removing Author from the managed property


text:
Q: IBM Bluemix Discovery - query parameter I have created a Discovery service on my bluemix account. I want to query my documents from a nodejs application.
I have built a query with some aggregation, tested it using the bluemix online tool and it's working well.
Now when I query the collection from my code, whatever my parameters are, I always receive all of my documents with the enriched text and so on. I think I am missing how to send the query attributes to the service (like filters and aggregations).
Here is my code:
var queryParams = {
  query:'CHLOE RICHARDS',
  return:'title',
  count:1,
  aggregations:'nested(enriched_text.entities).filter(enriched_text.entities.type:Person).term(enriched_text.entities.text, count:5)'
};

discovery.query({environment_id:that.environment_id, collection_id:that.collection_id, query_options:queryParams }, function(error, data) {
  if(error){
    console.error(error);
    reject(error);
  }
  else{
    console.log(JSON.stringify(data, null, 2));
    resolve(data.matching_results);
  }
});

And the result is always:
{
  "matching_results": 28,
  "results": [
    {
      "id": "fe5e2a38e6cccfbd97dbdd0c33c9c8fd",
      "score": 1,
      "extracted_metadata": {
        "publicationdate": "2016-01-05",
        "sha1": "28434b0a7e2a94dd62cabe9b5a82e98766584dd412",
        "author": "Richardson, Heather S",
        "filename": "whatever.docx",
        "file_type": "word",
        "title": "no title"
      },
      "text": "......

Independantly of the value of the query_optionparameter. Can you help me?
EDIT
Instead of the query_options:queryParams, I have used  query:"text:CHLOE RICHARDS" and it's working well. Now my problem still remains to find the right parameter format to add the aggregations I want
EDIT 2
So I have looked at IBM's example on Github more carefully, and the parameters are now formatted like this:
const queryParams = {
  count: 5,
  return: 'title,enrichedTitle.text',
  query: '"CHLOE RICHARDS"',
  aggregations: [ 'nested(enriched_text.entities).filter(enriched_text.entities.type:Person).term(enriched_text.entities.text, count:5)' ],
  environment_id: '1111111111',
  collection_id: '11111111111'
};

It works well if I use only the query attribute. Now if I only use the aggregations one, all the documents are sent back as a result (which is understandable) but I have no aggregation part, so I can not access the list of proper name in my documents.

A: Your query does not look right. I you are going to use query then you will need to construct a query search like text:"CHLOE RICHARDS"
If you want to perform a natural language query then you should be setting the parameter natural_language_query.


text:
Q: What is the group/party size in Lord of the Rings Online? How large of a group can you play Lord of the Rings online with? Is it a group/party based game?
I play PC games with a group of 4-5 people and we are looking for something we can all play together online.  Does LOTR Online fit that criteria?
We currently play Guild Wars, but we are running out of content there, and have been thinking of something different to start playing.

A: The maximum group size in LOTR: Online is 6 players.
I started playing LOTR after playing Guild Wars and I feel like it's very group oriented. The quests are all varying degrees of difficulty; some of them are recommended only for parties. The guilds that I've come across in LOTR are very active and friendly. There's a ton of content apart from the main storyline and new content gets added on a weekly basis. It should keep your interest for quite a while.

A: You can group up to 24 players. A group have the maximum of 6 players and a raid of 24 players. The grouping is seperated into 4 categories:

*

*small group (3 players)

*groups (6 players)

*raid (12 players)

*large raid (24 players)

You can complete most of quests while in group and within up to normal group size (6 or lower) without any backdraw. The exception are raid dungeons and quests and some instanced dungeons you have to complete in small group size (3 or lower). Most instanced dungeons are designed for normal group size (6). Btw. there is NO scaling. You should go into the dungeon with the suggested group size. There IS a level scaling for some dungeons as the "Great Barrows" dungeon.

A: Max Fellowship (group) size, is 6
However:

*

*Small Fellowship = 3

*Full Fellowship = 6

*Half-Raid = 12

*Full-Raid = 24

However, do note that some quests, if done without a fellowship when a fellowship is required, will give you Inspiration. Inspiration gives you a massive health boost (300%), a massive power boost (250ish%), +250% damage, +3000 regeneration rate. Basically, it's a "God Mode" because you are practically invincible. Some quests are: Vol 1, Bk 2, "The Red Pass", All of Vol 1, Bk 3. Those are the Inspiration quests I have done. There are many more.
Check the lorebook/lotro-wiki.com for more.
Edit: Please note that Skirmishes, can be scaled from Solo to Half-Raid.
Edit: Also note that Private Instances can be scaled for just the LEVEL, but not all of them, like GA.


text:
Q: How to pass a AJAX call on OctoberCMS Im using OctoberCMS, the user plugin and I want to send data via AJAX to a controller and save the data in the database (in the column of the logged in user).
So I created a new Route in my routes.php
<?php
Route::get('saveHighscore', 'test\Profile\Controllers\HighScore@saveHighscore')
->middleware('web');

And a controller
<?php
namespace Test\Profile\Controllers;

use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use October\Rain\Auth\Models\User;
use RainLab\User\Facades\Auth;

class HighScore extends \Illuminate\Routing\Controller
{
function saveHighscore(Request $request) {
    DB::table('users')->where(['id' => Auth::getUser()->id])->update(['highscore' => $request]);
}
}

And my jQuery calls
$.ajax({
        headers: {
            'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
        },
        url: "/saveHighscore",
        type: "POST",
        data: highscore
    });

But nothing works. If I call /saveHighscore in my browser with dummy data in the controller, it works fine

A: The AJAX framework only works on the CMS controller or Backend controllers (controllers extending backend/classes/controller). If you're wanting to send data via AJAX without using the built in AJAX framework, then we would have to see more information from your console / network tab of your browser dev tools to see why exactly it's failing.

A: It should work without any issue.
But I think you are making 2 different requests

In ajax config you specified -> type: "POST" and you are listening for get request

May be you just need to change Route::get -> Route::post
Now it should work expected.
If any doubts please comment.


text:
Q: Trying to write an IF ( Match ); possible syntax error? Highly likely this is a syntax error, but it's not throwing any errors.
=IF(ISERROR(MATCH(MID(Z2,28,6),$AF$1:$AG1,0)),"Mismatch","Included")

I have Z2, Z2 contains the following text:
"Revenue account for invoice P13930."
Or something like that, so the Mid function is suppoused to match that code, P13930, and not if it is within the specified cells (Here, AF1 and AG1)
I tried copying the whole text, or even just the code to AF1 and AG1, but it never writes a match. What's wrong with it?
Based it on my prototype:
=IF(ISERROR(MATCH($AE1,$AF1:$AG$1,0)),"Mismatch","Included")

Which does happen to work.
EDIT: I forgot to mention, I was wondering how to include the following scenarios:
Sometimes the code would look like this: P13930. and other times like this: P13930A. I'm not sure how to consider these as my knowledge is limited to Mid , Left , and Right. And as Jordan Mentioned, MATCH would be out of the picture given these variations.

A: Could you please specify your question:
First which we can advice, is to correct mid function argument:
=IF(ISERROR(MATCH(MID(Z2,29,6),$AF$1:$AG1,0)),"Mismatch","Included")
MID(Z2,29,6) - will give you result P13930
and then you want to find this code in some area, don't you? for example in the area AF1:AG1.
Please specify the result which you want to see in the cell AF2:
(a) code P13930; (b) INCLUDED - if area AF1:AG1 includes code P13930; (c) MISMATCHED - if area AF1:AG1 does NOT include code P13930 and etc.

A: If AF1 and AG1 contain codes like P13930A, you can use a wild card to match them like this
=IF(ISERROR(MATCH(MID(Z2,29,6)&"*",$AF$1:$AG1,0)),"Mismatch","Included")


text:
Q: VBA looping issue. Only works on current tab I am looking for a way with VBA in excel to loop through spreadsheet.  I found a lot of sites with recommendations on using a range function, but nothing specific enough that has solve the issues that I have. Macro will only work on current tab.  It will not loop through.
Sub UpdateAll()
'
' UpdateAll Macro
'

Dim ws As Worksheet
For Each ws In ActiveWorkbook.Worksheets

Call Update_OI

Next ws

End Sub

Sub Update_OI()
'
' Update_OI Macro

Dim rng As Range

For Colx = 3 To 81

    Cells(10, Colx).Select

  If ActiveCell.Offset(-8, 0) = "X" Then GoTo 4

  If ActiveCell.Offset(-3, 0) = 0 Then GoTo 4

  If ActiveCell.Value = vbNullString Then GoTo 4

  If ActiveCell.Value <> vbNullString Then GoTo 1

1
    goalvalue = Cells(70, Colx).Value
    Range(Cells(69, Colx), Cells(69, Colx)).GoalSeek Goal:=goalvalue, ChangingCell:=Range(Cells(10, Colx), Cells(10, Colx))

4
Next Colx

End Sub

A: You can pass the sheet object to Update_OI, and try not to use Select/Activate - you can almost always avoid that, and doing so will make your code more robust.
Sub UpdateAll()
    Dim ws As Worksheet
    For Each ws In ActiveWorkbook.Worksheets
        Update_OI ws
    Next ws
End Sub

Sub Update_OI(ws as Worksheet)
    Dim rng As Range, Colx As Long

    For Colx = 3 To 81

        Set rng = ws.Cells(10, Colx)

        If rng.Offset(-8, 0).Value <> "X" And _
           rng.Offset(-3, 0).Value <> 0 And _
           Len(rng.Value) > 0 Then

            goalvalue = ws.Cells(70, Colx).Value

            ws.Cells(69, Colx).GoalSeek Goal:=goalvalue, _
                   ChangingCell:=ws.Cells(10, Colx)
        End If

    Next Colx

End Sub

A: Below code works
Public Sub main()
    Dim ws As Worksheet
    For Each ws In ActiveWorkbook.Worksheets
        ws.Cells(1, 2).Value = 11111
    Next ws
End Sub

Try changing
Dim ws As Worksheet For Each ws In ActiveWorkbook.Worksheets
     Call Update_OI
Next ws

To
Dim ws As Worksheet
For Each ws In ActiveWorkbook.Worksheets
     Call Update_OI
Next ws

Or was it just copy paste formating problem. In this case I will remove my answer as it si no answer :).

A: Change your update all as below. It should work now.
Sub UpdateAll()
   Dim ws As Worksheet
   For Each ws In ActiveWorkbook.Worksheets
        ws.Select
        Call Update_OI
    Next ws

  End Sub


text:
Q: NextJS не работаютстили в компоненте В NextJs сделал компонент с кастомным курсором, импортирую в него css молуль, но стили не применились, и className тоже отсутствует. Сам компонент я импортирую на главной странице с помощью dynamic import и { ssr: false }, чтобы был доступ к window браузера. Кто-то сталкивался? Не понятно почему отсутствуют стили

import { userEffec, useRef } from 'react'
import s from './Cursor.module.scss'

export default function Cursor() {
    const delay = 18;

    const dot = useRef<HTMLDivElement>(null);
    const dotOutline = userRef<HTMLDivElement>(null);

    const cursorVisible = useRef(true)
    const cursorEnlarged = useRef(false)

    const endX = useRef(window.innerWidth / 2);
    const endY = useRef(window.innerHeight / 2);
    const _x = useRef(0);
    const _y = useRef(0)

    const requestRef = userRef(null);
}

import Head from 'next/head'
import Image from 'next/image'
import { Inter } from '@next/font/google'
import styles from '@/style/Home.module.scss'
const Cursor = dynamic(() => import("../components/Cursor/Cursor"), { ssr: false }):

const inter = Inter({ subsets: ['latin'] })

A: В Next Js все стили нужно хранить в папке styles в корневом проекте. Перемести модульный стиль в папку styles.
В импорте у тебя должно быть import s from '@/styles/Cursor.module.sсss'


text:
Q: how to print just filename without using __FILE__ in C I want to print the filename that is being used in my project.
But if I use __FILE__, it prints entire path along with the file name which is long in my case and disturbs the log indents.
Can anyone please help how I can print just the file name using a common parameter across my project.

A: In your C code, you might use instead of __FILE__ the expression basename(__FILE__); however, this has the disadvantage of calling basename at every occurrence.
Alternatively, compile path/foo.c  with a command like
gcc -Wall -c -g -DBASE_FILE=\"foo\" path/foo.c

(you could have a generic make rule giving that : with GNU make use functions like basename and automatic variables )
then use BASE_FILE instead of __FILE__ in your code.
With GCC, you could use __BASE_FILE__ instead of __FILE__

A: Consider using basename. I don't think the preprocessor gives you much more than __FILE__.