text:
Q: JSDOM not loading script files in Node I am trying to do a test of loading up an html page in jsdom which will eventually generate graphs.  I cannot overcome the first hurdle of just loading the html page and having the javascript execute.
Below is my html page which I am trying to load which doesnt take any parameters and just renders a simple graph.

Charts will render here

Here is the code in node where I am trying to load this page..
    var config = {
    file: path.join(__dirname, "chart.html"),
    features:{
      FetchExternalResources: ["script"],
      ProcessExternalResources: ["script"],
      MutationEvents: '2.0'
    },
    scripts:[
      "http://code.jquery.com/jquery.min.js",
      "http://static.fusioncharts.com/code/latest/fusioncharts.js",
      'http://static.fusioncharts.com/code/latest/fusioncharts.charts.js',
      "http://static.fusioncharts.com/code/latest/themes/fusioncharts.theme.fint.js"
    ],
    onload: function(err, window) {
      console.log('*******onload')
    },
    created: function(err, window) {
      console.log('*******created')
    },
    done: function(err, window) {
      console.log('*******done')
      if(err){
        console.log('*****got err ' + err.message);
        callback(err);
      }

      global.window = window;
      console.log('inside done ----------')
      var $ = window.jQuery || window.$,
      FusionCharts = window.FusionCharts,
      document = window.document;

      if(typeof FusionCharts == 'undefined')
        console.log('FusionCharts NOT LOADED')
      else
        console.log('FusionCharts LOADED')

      if(typeof $ == 'undefined')
        console.log('JQUERY NOT LOADED')
      else
        console.log('JQUERY LOADED')

      console.log('testVar ' + window.testVar)
      console.log(window.test())
      console.log('testVar ' + window.testVar)
      console.log('svg is ' + window.svg);
      console.log($('#container').html());

      window.close();

    }
  }
  jsdom.env(config);

The strange thing here is that if i do not include scripts in the config object, it will not load them and make them available in the done callback even thought it is there on the html page.
Also, testVar is never defined in the callback even thought it is present in the page, the same with window.test(), even though its in the html page it just does not seem to be available in the callback.
I have tried all different variations of creating the jsdom object, but none of them allows the page to load the scripts rather than me passing it into the config object, and none of the different versions allow me to access variables and functions defined in the script tags.
Is there something I am missing ?

A: Change your script elements so that they are correct HTML:

If you do that everything will load fine and you won't have to use scripts in your configuration.


text:
Q: How can I automatically populate the VBA Editor with line numbers? I want to have line numbers in my VBA code for debugging reasons. That will allow me to know where a particular error occurred.
Is there an automatic feature for this (such as an option in settings)? Or do I need to write my own macro?
If I need to write my own macro to accomplish this task, how would I go about doing such a thing?

A: I use this code for adding line numbers to my Excel projects. I found it online a while back and I don't remember where I got it, so credit goes to whoever originally wrote this:
Sub AddLineNumbers(wbName As String, vbCompName As String)
    'See MakeUF
    Dim i As Long, j As Long, lineN As Long
    Dim procName As String
    Dim startOfProceedure As Long
    Dim lengthOfProceedure As Long
    Dim newLine As String

    With Workbooks(wbName).VBProject.VBComponents(vbCompName).CodeModule
        .CodePane.Window.Visible = False

        For i = 1 To .CountOfLines
            procName = .ProcOfLine(i, vbext_pk_Proc)

            If procName <> vbNullString Then
                startOfProceedure = .ProcStartLine(procName, vbext_pk_Proc)
                lengthOfProceedure = .ProcCountLines(procName, vbext_pk_Proc)

                If startOfProceedure + 1 < i And i < startOfProceedure + lengthOfProceedure - 1 Then
                    newLine = RemoveOneLineNumber(.Lines(i, 1))
                    If Not HasLabel(newLine) And Not (.Lines(i - 1, 1) Like "* _") Then
                        .ReplaceLine i, CStr(i) & ":" & newLine
                    End If
                End If
            End If

        Next i
        .CodePane.Window.Visible = True
    End With
End Sub

Sub RemoveLineNumbers(wbName As String, vbCompName As String)
    'See MakeUF
    Dim i As Long
    With Workbooks(wbName).VBProject.VBComponents(vbCompName).CodeModule
        For i = 1 To .CountOfLines
            .ReplaceLine i, RemoveOneLineNumber(.Lines(i, 1))
        Next i
    End With
End Sub

Function RemoveOneLineNumber(aString)
    RemoveOneLineNumber = aString
    If aString Like "#:*" Or aString Like "##:*" Or aString Like "###:*" Then
        RemoveOneLineNumber = Mid(aString, 1 + InStr(1, aString, ":", vbTextCompare))
    End If
End Function

Function HasLabel(ByVal aString As String) As Boolean
    HasLabel = InStr(1, aString & ":", ":") < InStr(1, aString & " ", " ")
End Function

You'll have to modify it to suit your needs since you're working in Access, but I'm sure the main meat of it still applies. In Excel, there's a userform that is used to kick off the code for the module you specify, but you should be able to just pass in the module name (vbCompName) to specify the module. I'm not well-versed in Access VBA, so I'm not sure what you'd replace Workbooks(wbName) with in the code.

A: The VBA editor has a built in way to see a line number, under the 'Standard' toolbar:

When you select a line of code, the line number will be represented here next to 'Ln'.

A: You don't want line numbers.
Not for "debugging reasons", not for anything. Line numbers are deprecated for a reason: they're a relic of an ancient time before procedures even existed, and GOTO the only way to get anywhere.
Erl only returns the last encountered line number before an error was raised. This can mean misleading error logs, if you're logging errors:
Sub DoSomething()
10 On Error GoTo 50
   Debug.Print 42 / 0
30 Exit Sub

50 Debug.Print "Error raised on line " & Erl 'returns 10
End Sub

Also, line numbers only have Integer resolution (a VBA module can have up to 65,535 lines, which is twice that resolution), and will silently fail and happily report wrong line numbers if you don't keep that in mind:
Sub DoSomething()
99997 On Error GoTo 99999
99998 Debug.Print 42 / 0
99999
      Debug.Print Erl   'Prints 34462 - and which line is that?
End Sub

Any serious VBA application will use structured error handling instead.
Write small, specialized procedures (i.e. write code that follows modern-day best practices), and the line number becomes utterly meaningless.
Line numbers are a pain in the neck to maintain; they clutter up the code and make it overall harder to read (and therefore to debug).

That said, IIRC MZ-Tools 3 had such a functionality.
Keep in mind, that BASIC looked like this when line numbers were a thing:
10 GOSUB 100
20 GOSUB 1000
99 END
100 REM CLEAR SCREEN
110 PRINT CHR$(147)
120 RETURN
200 REM MODULO
210 LET MOD% = V%-INT(V%/FB%)*FB%
220 RETURN
1000 REM INIT VARIABLES
1010 LET FIZZ$ = "FIZZ"
1011 LET BUZZ$ = "BUZZ"
1020 LET FIZZ% = 3
1021 LET BUZZ% = 5
1030 LET MIN% = 1
1031 LET MAX% = 15
1100 PRINT FIZZ$ + ":" + STR$(FIZZ%)
1101 PRINT BUZZ$ + ":" + STR(BUZZ%)
1102 PRINT FIZZ$ + BUZZ$ + ":" + STR$(FIZZ%*BUZZ%)
1105 PRINT
2000 REM ACTUAL FIZZBUZZ LOOP
2010 FOR X = MIN% TO MAX%
2015 LET RESULT$ = STR$(X)
2020 LET FB% = FIZZ%*BUZZ%
2021 LET V% = X
2024 GOSUB 200
2025 IF MOD%=0 THEN LET RESULT$=FIZZ$+BUZZ$ : GOTO 2050
2030 LET FB% = FIZZ%
2031 GOSUB 200
2035 IF MOD%=0 THEN LET RESULT$=FIZZ$ : GOTO 2050
2040 LET FB% = BUZZ%
2041 GOSUB 200
2045 IF MOD%=0 THEN LET RESULT$=BUZZ$ : GOTO 2050
2050 PRINT RESULT$
2090 NEXT X
2099 RETURN

The above is a working Commodore 64 BASIC 2.0 fizzbuzz program. VBA has fabulous backward-compatibility. With only slight modifications, it runs in VBA:
Sub Main()
10     GoSub 100
20     GoSub 1000
99     End
100     Rem CLEAR SCREEN
110     'Debug.Print Chr$(147) 'Chr$(147) was a special character on C64
120     Return
200     Rem MODULO
210     Let Modulo% = V% - Int(V% / FB%) * FB%
220     Return
1000     Rem INIT VARIABLES
1010     Let FIZZ$ = "FIZZ"
1011     Let BUZZ$ = "BUZZ"
1020     Let FZZ% = 3
1021     Let BZZ% = 5
1030     Let Min% = 1
1031     Let Max% = 15
1100     Debug.Print FIZZ$ + ":" + Str$(FZZ%)
1101     Debug.Print BUZZ$ + ":" + Str(BZZ%)
1102     Debug.Print FIZZ$ + BUZZ$ + ":" + Str$(FZZ% * BZZ%)
1105     Debug.Print
2000     Rem ACTUAL FIZZBUZZ LOOP
2010     For X = Min% To Max%
2015     Let RESULT$ = Str$(X)
2020     Let FB% = FZZ% * BZZ%
2021     Let V% = X
2024     GoSub 200
2025     If Modulo% = 0 Then Let RESULT$ = FIZZ$ + BUZZ$: GoTo 2050
2030     Let FB% = FZZ%
2031     GoSub 200
2035     If Modulo% = 0 Then Let RESULT$ = FIZZ$: GoTo 2050
2040     Let FB% = BZZ%
2041     GoSub 200
2045     If Modulo% = 0 Then Let RESULT$ = BUZZ$: GoTo 2050
2050     Debug.Print RESULT$
2090     Next X
2099     Return
End Sub

Don't write 1980's code, we're 40 years later.

A: MZ-Tools for VBA has functions to add and remove line numbers to single functions, modules, or the whole project.
See http://www.mztools.com/v8/onlinehelp/index.html?add_remove_line_numbers.htm
Note 1: I find it better to configure the line number increment to 1 instead of 10. You will never manually add line numbers inbetween - whenever you edit the code, you first remove the line numbers, then add them back when you are finished.
Note 2: Until a few years ago, there was a free version 3.0 of MZ-Tools, but it is surprisingly difficult to find a copy. But it is a good investment - there are lots of other useful features (e.g. the automatic adding of error handlers).

A: The answer of Arich works like a charm on an individual module. If you want to provide your entire workbook with (updated) line numbers you apply the following steps*^:
Do Once:

*

*Paste the large code from  Module2 in your workbook.

*Paste the code for  Module3  in your workbook.

*Paste the code for  Module4  in your workbook.

*Then paste the line Global allow_for_line_addition As Stringthis is just so that you can automatically add linenumbers` above/in the first line of every
module.

*Delete all empty lines at the end of each module (so no lose enters after the last end sub,end function or End Property of a module).

*In the VBA editor, while not running a code, and not being in "break"-mode:click tools>references>mark: `Microsoft Visual Basic for Applications Extensibility 5.3"

Do every time you have modified your code:

*°Run the code for  Module3 to remove line numbers to all the modules in your workbook.

*°Run the code for  Module4 to add line numbers to all the modules in your workbook.

Module2:
    Public Enum vbLineNumbers_LabelTypes
        vbLabelColon    ' 0
        vbLabelTab      ' 1
    End Enum

    Public Enum vbLineNumbers_ScopeToAddLineNumbersTo
        vbScopeAllProc  ' 1
        vbScopeThisProc ' 2
    End Enum
              Sub AddLineNumbers(ByVal wbName As String, _
                                                          ByVal vbCompName As String, _
                                                          ByVal LabelType As vbLineNumbers_LabelTypes, _
                                                          ByVal AddLineNumbersToEmptyLines As Boolean, _
                                                          ByVal AddLineNumbersToEndOfProc As Boolean, _
                                                          ByVal Scope As vbLineNumbers_ScopeToAddLineNumbersTo, _
                                                          Optional ByVal thisProcName As String)

    ' USAGE RULES
    ' DO NOT MIX LABEL TYPES FOR LINE NUMBERS! IF ADDING LINE NUMBERS AS COLON TYPE, ANY LINE NUMBERS AS VBTAB TYPE MUST BE REMOVE BEFORE, AND RECIPROCALLY ADDING LINE NUMBERS AS VBTAB TYPE

        Dim i As Long
        Dim j As Long
        Dim procName As String
        Dim startOfProcedure As Long
        Dim lengthOfProcedure As Long
        Dim endOfProcedure As Long
        Dim strLine As String

        With Workbooks(wbName).VBProject.VBComponents(vbCompName).CodeModule
            .CodePane.Window.Visible = False

    If Scope = vbScopeAllProc Then

            For i = 1 To .CountOfLines - 1

                strLine = .Lines(i, 1)
                procName = .ProcOfLine(i, vbext_pk_Proc) ' Type d'argument ByRef incompatible ~~> Requires VBIDE library as a Reference for the VBA Project

                If procName <> vbNullString Then
                    startOfProcedure = .ProcStartLine(procName, vbext_pk_Proc)
                    bodyOfProcedure = .ProcBodyLine(procName, vbext_pk_Proc)
                    countOfProcedure = .ProcCountLines(procName, vbext_pk_Proc)

                    prelinesOfProcedure = bodyOfProcedure - startOfProcedure
                    'postlineOfProcedure = ??? not directly available since endOfProcedure is itself not directly available.

                    lengthOfProcedure = countOfProcedure - prelinesOfProcedure ' includes postlinesOfProcedure !
                    'endOfProcedure = ??? not directly available, each line of the proc must be tested until the End statement is reached. See below.

                    If endOfProcedure <> 0 And startOfProcedure < endOfProcedure And i > endOfProcedure Then
                        GoTo NextLine
                    End If

                    If i = bodyOfProcedure Then inprocbodylines = True

                    If bodyOfProcedure < i And i < startOfProcedure + countOfProcedure Then
                        If Not (.Lines(i - 1, 1) Like "* _") Then

                            inprocbodylines = False

                            PreviousIndentAdded = 0

                            If Trim(strLine) = "" And Not AddLineNumbersToEmptyLines Then GoTo NextLine

                            If IsProcEndLine(wbName, vbCompName, i) Then
                                endOfProcedure = i
                                If AddLineNumbersToEndOfProc Then
                                    Call IndentProcBodyLinesAsProcEndLine(wbName, vbCompName, LabelType, endOfProcedure)
                                Else
                                    GoTo NextLine
                                End If
                            End If

                            If LabelType = vbLabelColon Then
                                If HasLabel(strLine, vbLabelColon) Then strLine = RemoveOneLineNumber(.Lines(i, 1), vbLabelColon)
                                If Not HasLabel(strLine, vbLabelColon) Then
                                    temp_strLine = strLine
                                    .ReplaceLine i, CStr(i) & ":" & strLine
                                    new_strLine = .Lines(i, 1)
                                    If Len(new_strLine) = Len(CStr(i) & ":" & temp_strLine) Then
                                        PreviousIndentAdded = Len(CStr(i) & ":")
                                    Else
                                        PreviousIndentAdded = Len(CStr(i) & ": ")
                                    End If
                                End If
                            ElseIf LabelType = vbLabelTab Then
                                If Not HasLabel(strLine, vbLabelTab) Then strLine = RemoveOneLineNumber(.Lines(i, 1), vbLabelTab)
                                If Not HasLabel(strLine, vbLabelColon) Then
                                    temp_strLine = strLine
                                    .ReplaceLine i, CStr(i) & vbTab & strLine
                                    PreviousIndentAdded = Len(strLine) - Len(temp_strLine)
                                End If
                            End If

                        Else
                            If Not inprocbodylines Then
                                If LabelType = vbLabelColon Then
                                    .ReplaceLine i, Space(PreviousIndentAdded) & strLine
                                ElseIf LabelType = vbLabelTab Then
                                    .ReplaceLine i, Space(4) & strLine
                                End If
                            Else
                            End If
                        End If

                    End If

                End If

    NextLine:
            Next i

    ElseIf AddLineNumbersToEmptyLines And Scope = vbScopeThisProc Then

    End If

            .CodePane.Window.Visible = True
        End With

    End Sub
              Function IsProcEndLine(ByVal wbName As String, _
                  ByVal vbCompName As String, _
                  ByVal Line As Long) As Boolean

    With Workbooks(wbName).VBProject.VBComponents(vbCompName).CodeModule
    If Trim(.Lines(Line, 1)) Like "End Sub*" _
                Or Trim(.Lines(Line, 1)) Like "End Function*" _
                Or Trim(.Lines(Line, 1)) Like "End Property*" _
                Then IsProcEndLine = True
    End With

    End Function
              Sub IndentProcBodyLinesAsProcEndLine(ByVal wbName As String, ByVal vbCompName As String, ByVal LabelType As vbLineNumbers_LabelTypes, ByVal ProcEndLine As Long)
        Dim procName As String
        Dim startOfProcedure As Long
        Dim endOfProcedure As Long

        With Workbooks(wbName).VBProject.VBComponents(vbCompName).CodeModule

            procName = .ProcOfLine(ProcEndLine, vbext_pk_Proc)
            bodyOfProcedure = .ProcBodyLine(procName, vbext_pk_Proc)
            endOfProcedure = ProcEndLine
            strEnd = .Lines(endOfProcedure, 1)

            j = bodyOfProcedure
            Do Until Not .Lines(j - 1, 1) Like "* _" And j <> bodyOfProcedure

                strLine = .Lines(j, 1)

                If LabelType = vbLabelColon Then
                    If Mid(strEnd, Len(CStr(endOfProcedure)) + 1 + 1 + 1, 1) = " " Then
                        .ReplaceLine j, Space(Len(CStr(endOfProcedure)) + 1) & strLine
                    Else
                        .ReplaceLine j, Space(Len(CStr(endOfProcedure)) + 2) & strLine
                    End If
                ElseIf LabelType = vbLabelTab Then
                    If endOfProcedure < 1000 Then
                        .ReplaceLine j, Space(4) & strLine
                    Else
                        Debug.Print "This tool is limited to 999 lines of code to work properly."
                    End If
                End If

                j = j + 1
            Loop

        End With
    End Sub
              Sub RemoveLineNumbers(ByVal wbName As String, ByVal vbCompName As String, ByVal LabelType As vbLineNumbers_LabelTypes)
        Dim i As Long
        With Workbooks(wbName).VBProject.VBComponents(vbCompName).CodeModule
            'MsgBox ("nr of lines = " & .CountOfLines & vbNewLine & "Procname = " & procName)
                'MsgBox ("nr of lines REMEMBER MUST BE LARGER THAN 7! = " & .CountOfLines)
            For i = 1 To .CountOfLines
                procName = .ProcOfLine(i, vbext_pk_Proc)
                If procName <> vbNullString Then
                    If i > 1 Then
                            'MsgBox ("Line " & i & " is a body line " & .ProcBodyLine(procName, vbext_pk_Proc))
                        If i = .ProcBodyLine(procName, vbext_pk_Proc) Then inprocbodylines = True
                            If .Lines(i - 1, 1) <> "" Then
                                'MsgBox (.Lines(i - 1, 1))
                            End If
                        If Not .Lines(i - 1, 1) Like "* _" Then
                            'MsgBox (inprocbodylines)
                            inprocbodylines = False
                                'MsgBox ("recoginized a line that should be substituted: " & i)
                            'MsgBox ("about to replace " & .Lines(i, 1) & vbNewLine & " with: " & RemoveOneLineNumber(.Lines(i, 1), LabelType) & vbNewLine & " with label type: " & LabelType)
                            .ReplaceLine i, RemoveOneLineNumber(.Lines(i, 1), LabelType)
                        Else
                            If IsInProcBodyLines Then
                                ' do nothing
                                    'MsgBox (i)
                            Else
                                .ReplaceLine i, Mid(.Lines(i, 1), RemovedChars_previous_i + 1)
                            End If
                        End If
                    End If
                Else
                ' GoTo NextLine
                End If
    NextLine:
            Next i
        End With
    End Sub
              Function RemoveOneLineNumber(ByVal aString As String, ByVal LabelType As vbLineNumbers_LabelTypes)
        RemoveOneLineNumber = aString
        If LabelType = vbLabelColon Then
            If aString Like "#:*" Or aString Like "##:*" Or aString Like "###:*" Or aString Like "####:*" Then
                RemoveOneLineNumber = Mid(aString, 1 + InStr(1, aString, ":", vbTextCompare))
                If Left(RemoveOneLineNumber, 2) Like " [! ]*" Then RemoveOneLineNumber = Mid(RemoveOneLineNumber, 2)
            End If
        ElseIf LabelType = vbLabelTab Then
            If aString Like "#   *" Or aString Like "##  *" Or aString Like "### *" Or aString Like "#### *" Then RemoveOneLineNumber = Mid(aString, 5)
            If aString Like "#" Or aString Like "##" Or aString Like "###" Or aString Like "####" Then RemoveOneLineNumber = ""
        End If
    End Function
              Function HasLabel(ByVal aString As String, ByVal LabelType As vbLineNumbers_LabelTypes) As Boolean
        If LabelType = vbLabelColon Then HasLabel = InStr(1, aString & ":", ":") < InStr(1, aString & " ", " ")
        If LabelType = vbLabelTab Then
            HasLabel = Mid(aString, 1, 4) Like "#   " Or Mid(aString, 1, 4) Like "##  " Or Mid(aString, 1, 4) Like "### " Or Mid(aString, 1, 5) Like "#### "
        End If
    End Function
              Function RemoveLeadingSpaces(ByVal aString As String) As String
        Do Until Left(aString, 1) <> " "
            aString = Mid(aString, 2)
        Loop
        RemoveLeadingSpaces = aString
    End Function
              Function WhatIsLineIndent(ByVal aString As String) As String
        i = 1
        Do Until Mid(aString, i, 1) <> " "
            i = i + 1
        Loop
        WhatIsLineIndent = i
    End Function

              Function HowManyLeadingSpaces(ByVal aString As String) As String
        HowManyLeadingSpaces = WhatIsLineIndent(aString) - 1
    End Function

Module3:
    Global allow_for_line_addition As String 'this is just so that you can automatically add linenumbers
            Sub remove_line_numbering_all_modules()
    'source: https://stackoverflow.com/questions/36791473/vba-getting-the-modules-in-workbook
    'This code numbers all the modules in your .xlsm
        Dim vbcomp As VBComponent
        Dim modules As Collection
    Set modules = New Collection
        For Each vbcomp In ThisWorkbook.VBProject.VBComponents
            'if normal or class module
            If ((vbcomp.Type = vbext_ct_StdModule) Or (vbcomp.Type = vbext_ct_ClassModule)) Then
                   'V0:
                   RemoveLineNumbers wbName:=ThisWorkbook.name, vbCompName:=vbcomp.name, LabelType:=vbLabelColon
                   'V1:
                   'Call RemoveLineNumbers(ThisWorkbook.name, vbcomp.name)
            End If
        Next vbcomp
    End Sub

Module4:
    Global allow_for_line_addition As String 'this is just so that you can automatically add linenumbers
    'This sub adds line numbers to all the modules after you have added the following line to every module
    'add tools references microsoft visual basic for applications (5.3) as checked
    'Source httpsstackoverflow.comquestions40731182excel-vba-how-to-turn-on-line-numbers-in-code-editor50368332#50368332
            Sub add_line_numbering_all_modules()
    'source: https://www.stackoverflow.com/questions/36791473/vba-getting-the-modules-in-workbook
    'This code numbers all the modules in your .xlsm
        Dim vbcomp As VBComponent
        Dim modules As Collection
        Set modules = New Collection
        For Each vbcomp In ThisWorkbook.VBProject.VBComponents
            'if normal or class module
            If ((vbcomp.Type = vbext_ct_StdModule) Or (vbcomp.Type = vbext_ct_ClassModule)) Then
                   'V0:
                   Call AddLineNumbers(ThisWorkbook.name, vbcomp.name, vbLabelColon, True, True, vbScopeAllProc)
                   'v1
                   'Call AddLineNumbers(ThisWorkbook.name, vbcomp.name)
            End If
        Next vbcomp
    End Sub

where you can either substitute "Book1.xlsm" with the name of your own workbook, or with thisworkbook (notice no ""), or vice versa.

*

**Note this worked in excel 2016, I have not tried it in 2013 yet.

*^It is a modified version of Hemced's answer here., which in turn, looks a lot like Arich's answer.

*°because sometimes you get an error if you cut lines out or move them around (e.g. put line 2440: above line 2303:). By removing and re-adding them, the line numbering is automatically correct again.

A: This Works for me...Add this to its own module. Calling the code will toggle line numbers on or off. Adding Module titles and/or procedure titles in quotes will update only the module or procedure named.
    Option Compare Database
    Option Explicit

    Sub AddLineNumbers(Optional vbCompName As String, Optional vbCompSubName As String)
    On Error Resume Next

        DoCmd.Hourglass True
        Application.VBE.ActiveVBProject.References.AddFromGuid "{0002E157-0000-0000-C000-000000000046}", 5, 0
        Call ExecuteAddLineNumbers(vbCompName, vbCompSubName)
        DoCmd.Hourglass False

    End Sub

    Sub ExecuteAddLineNumbers(Optional vbCompName As String, Optional vbCompSubName As String)
    On Error GoTo Err_Handler

        'create a reference to the Microsoft Visual Basic for Applications Extensibility library
        Dim i As Long, j As Long, lineN As Long
        Dim procName As String
        Dim startOfProceedure As Long
        Dim lengthOfProceedure As Long
        Dim newLine As String
        Dim objComponent As Object
        Dim lineNumber As Long
        Dim HasLineNumbers As Boolean

        For Each objComponent In Application.VBE.ActiveVBProject.VBComponents
            If (vbCompName = vbNullString Or objComponent.Name = vbCompName) And objComponent.Name <> _
            Application.VBE.ActiveCodePane.CodeModule.Name) Then
                Debug.Print objComponent.Name
                With objComponent.CodeModule
                    .CodePane.Window.Visible = False
                    For i = 1 To .CountOfLines
                        'Debug.Print .ProcOfLine(i, vbext_pk_Proc)
                        If procName = "" And .ProcOfLine(i, vbext_pk_Proc) <> "" Then
                            procName = .ProcOfLine(i, vbext_pk_Proc)
                            'vbext_pk_Get    Specifies a procedure that returns the value of a property.
                            'vbext_pk_Let    Specifies a procedure that assigns a value to a property.
                            'vbext_pk_Set    Specifies a procedure that sets a reference to an object.
                            'vbext_pk_Proc   Specifies all procedures other than property procedures.
                            'type=vbext_ct_ClassModule
                            'type=vbext_ct_StdModule
                            'type=vbext_ct_Document
                            If objComponent.Type = vbext_ct_ClassModule Then
                                If InStr(.Lines(i + 1, 1), " Let ") > 0 Then
                                    startOfProceedure = .ProcStartLine(procName, vbext_pk_Let)
                                    lengthOfProceedure = .ProcCountLines(procName, vbext_pk_Let)
                                ElseIf InStr(.Lines(i + 1, 1), " Get ") > 0 Then
                                    startOfProceedure = .ProcStartLine(procName, vbext_pk_Get)
                                    lengthOfProceedure = .ProcCountLines(procName, vbext_pk_Get)
                                ElseIf InStr(.Lines(i + 1, 1), " Set ") > 0 Then
                                    startOfProceedure = .ProcStartLine(procName, vbext_pk_Set)
                                    lengthOfProceedure = .ProcCountLines(procName, vbext_pk_Set)
                                Else
                                    startOfProceedure = .ProcStartLine(procName, vbext_pk_Proc)
                                    lengthOfProceedure = .ProcCountLines(procName, vbext_pk_Proc)
                                End If
                            Else
                                startOfProceedure = .ProcStartLine(procName, vbext_pk_Proc)
                                lengthOfProceedure = .ProcCountLines(procName, vbext_pk_Proc)
                            End If
                            lineNumber = 10
                            HasLineNumbers = .Find("##  ", startOfProceedure + 1, 1, startOfProceedure + lengthOfProceedure - 1, 1, _
                            False, False, True)
                        End If

                        If (vbCompSubName = vbNullString And procName <> vbNullString) Or _
                           (vbCompSubName <> vbNullString And procName = vbCompSubName) Then

                            If startOfProceedure + 1 < i And i < startOfProceedure + lengthOfProceedure - 1 Then
                                newLine = RemoveOneLineNumber(.Lines(i, 1), HasLineNumbers)
                                If Trim(newLine) <> vbNullString Then
                                    If Not HasLabel(newLine) And Not (.Lines(i - 1, 1) Like "* _") Then
                                        If HasLineNumbers = False Then newLine = CStr(lineNumber) & vbTab & newLine
                                        .ReplaceLine i, newLine
                                        lineNumber = lineNumber + 10
                                    ElseIf Not HasLineNumbers Then
                                        .ReplaceLine i, vbTab & newLine
                                    Else
                                        .ReplaceLine i, newLine
                                    End If
                                End If
                            ElseIf i = startOfProceedure + lengthOfProceedure - 1 Then
                                procName = ""
                            End If
                        Else
                            procName = ""
                        End If

                    Next i
                    .CodePane.Window.Visible = True
                End With
            End If
        Next objComponent

    Exit Sub

    Err_Handler:
        MsgBox (Err.Number & ": " & Err.Description)

    End Sub

    Function RemoveOneLineNumber(aString As String, HasLineNumbers As Boolean)
        Dim i As Double
        RemoveOneLineNumber = aString
        i = ((Len(Trim(Str(Val(aString)))) / 4) - Int(Len(Trim(Str(Val(aString)))) / 4)) * 4
        If aString Like "#*" Then
            RemoveOneLineNumber = Space(i) & Mid(aString, InStr(1, aString, " ", vbTextCompare))
            RemoveOneLineNumber = Right(aString, Len(aString) - 4)
        ElseIf HasLineNumbers And aString Like "    *" Then
            RemoveOneLineNumber = Right(aString, Len(aString) - 4)
        End If
    End Function

    Function HasLabel(ByVal aString As String) As Boolean
        HasLabel = False
        If Right(Trim(aString), 1) = ":" Or _
            Left(Trim(aString), 3) = "Dim" Or _
            Left(Trim(aString), 3) = "ReDim" Or _
            Left(Trim(aString), 1) = "'" Or _
            Left(Trim(aString), 6) = "Option" Or _
            Left(Trim(aString), 5) = "Debug" Or _
            Left(Trim(aString), 3) = "Sub" Or _
            Left(Trim(aString), 11) = "Private Sub" Or _
            Left(Trim(aString), 10) = "Public Sub" Or _
            Left(Trim(aString), 8) = "Function" Or _
            Left(Trim(aString), 12) = "End Function" Or _
            Left(Trim(aString), 8) = "Property" Or _
            Left(Trim(aString), 12) = "End Property" Or _
            Left(Trim(aString), 7) = "End Sub" Then HasLabel = True

    End Function

A: Any decent error handler will report more than just a line number. It will report the error ode, description and the module where it happened. Regardless whether ERL is repeating line numbers throughout your app, if you can't find the problem with the other clues reported, maybe you need a sabbatical.  Or, hell, add a variable that increments a module level alpha code as an adjunct to the line number like "newERL = strProcLevel & ERL" to give you "A12345" as a line number.

A: This is not 100% tested, but using VBA extensibility you could do the following
Sub line_number(strModuleName As String)

Dim vbProj As VBProject
Dim vbComp As VBComponent
Dim cmCode As CodeModule
Dim intLine As Integer

Set vbProj = Application.VBE.ActiveVBProject
Set vbComp = vbProj.VBComponents(strModuleName)
Set cmCode = vbComp.CodeModule

For intLine = 2 To cmCode.CountOfLines - 1
   cmCode.InsertLines intLine, intLine - 1 &  cmCode.Lines(intLine, 1)
   cmCode.DeleteLines intLine + 1, 1
Next intLine

End Sub

This gives the results before and after as below, altering in this way is not recommended though.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Getting & setting values from xml in android I am new in android, I have a MainActivity.java in src and activity_main.xml in layout. If I create a button in activity_main.xml, then can I set or get the values of button properties in xml through MainActivity.java ?
how can change the property of PopupWindow like hieght,width through java

A: Yes you can modify the properties of your Views defined in a XML file.
For that, you have to put an ID in the View you want to modify in your activity_main.xml, for example:
<Button
    android:id="@+id/myButton"
    ... />

Then, in your MainActivity class, you can get this Button with the following method:
Button myButton = (Button) findViewById(R.id.myButton);

Now, you can add every property you want on this View. You can for example set its text:
myButton.setText("Click me!");

A: Yes you can.
Get the button:

Button button = findViewById(R.id.yourButtonId);

Get properties (some examples):

int x = button.getX;
int marginTop = ((ViewGroup.LayoutParams) button.getLayoutParams()).topMargin;

Set porperties:

button.setX = someValue;
((ViewGroup.LayoutParams) button.getLayoutParams()).topMargin = someValue;

A: Yes you can. All the XML attributes of any view has an equivalent java method.
for example you can change the text in XML using
android:text="Hello World!"

similarly you can change the text During runtime using java code like this:
textView1.setText("Hello World!");

both will give the same result.
[NOTE] remember that code in XML is predefined at compile time but the java code takes effect at runtime. i.e only after you run the app in the device/emulator. So you can't see the changes made by java code in the UI editor itself. Java code will only reflect during runtime.

A: In Xml file - you can set value for button as,
<Button
        android:id="@+id/button_Save"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="center"
        android:layout_weight="1"
        android:text="Save"
        />

To get the button values in a Java file then can use like this,
Button btn;
btn = (Button)findViewById(R.id.button_Save);

btn.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
String buttonText = btn.getText().toString();
Toast.makeText(MainActivity.this,"Button text is:" +buttonText,Toast.LENGTH_LONG).show();

        }
    });

A: You can get the properties defined in xml dynamically. But you cant write to those xml files (eg color, strings, dimen etc)
Example to set Button properties
<Button
                android:id="@+id/seeLater"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:background="@drawable/btn_message"
                android:fontFamily="sans-serif-condensed"
                android:gravity="center"
                android:text="@string/dialog_read_later"
                android:textColor="@color/White"
                android:textSize="@dimen/settings_tile_heading_size"
                android:focusableInTouchMode="true"/>

Following xml files under res folder to define properties
colors.xml
<?xml version="1.0" encoding="utf-8"?>
<resources>
    <color name="White">#ffffff</color>
</resources>

dimens.xml
<?xml version="1.0" encoding="utf-8"?>
<resources>
    <dimen name="settings_tile_heading_size">13sp</dimen>
</resources>

strings.xml
<?xml version="1.0" encoding="utf-8"?>
<resources>
<string name="dialog_read_later">LATER</string>
</resources>


text:
Q: Processing multiple Stripe payments simultaneously in Ruby My Rails project is processing multiple transactions at once through Stripe. I run this code with about 1000 orders and it takes about 3-4 minutes.  Is there a way to run them all at once?
    Order.each do |order|
      Stripe::Charge.create(
        :amount => 2000,
        :currency => "usd",
        :customer => order.customer,
        :card => order.card
      )
    end

A: There is no way to process multiple charges simultaneously (i.e., in a 'list') through the Stripe API; you need to do them one at a time.
You could speed this up by making multiple requests concurrently though, but don't make too many or you'll hit the rate limits.


text:
Q: How to add 2 individual MAC addresses along with port-security sticky command? I am designing my new company building network with Cisco 2960x and 3850ss switches and I want to use port-security for security reasons. I know how to configure 3 types of sticking MAC addresses to a port but I need to know if it is possible to stick some MAC addresses globally to all switches (for help-desk) and after that use port-security sticky command to switch learn latest connected MAC address automatically.

A: You cannot define it company wide, but per device. Use the interface range configuration to apply the configuration to all relevant ports of one device:
interface range Gi 0/1-20

Then set a maximum number of allowed MAC addresses:
switchport port-security maximum 3

Define the two MAC addresses of your help desk as static:
switchport port-security mac-address a1b1.c1d1.e1f1
switchport port-security mac-address a2b2.c2d2.e2f2

Define the ports as sticky afterwards:
switchport port-security mac-address sticky

You could apply this config company wide by using SNMP, SSH, etc. but not by a master device like it works with VTP.


text:
Q: Memcached ports and CSF I've got a small / medium sized VPS powered by WHM and running a few personal websites alongside a Magento powered web-store. Not being a real expert when it comes to server configuration details I've hired someone recently to oversee a memcached installation and which appears to work.
After some further reading on my own though I've stumbled upon a tutorial which mentioned that the related port (11211 in our case) has to be included / added to the TCP_IN" and "TCP_OUT" section of CSF which right now is clearly not the case in our installation.
Is this a real requirement? Can I feel free to add this related port and are there any advantages / disadvantages when doing this?
Some expert advise would be truly appreciated.
Thank you very much.

A: Actually, you do not want to open port 11211 in your firewall.
In your setup, memcached is running on the same machine, and localhost is rarely or never firewalled from itself since this causes the universe to implode. Thus processes on the same machine can talk to each other (e.g. PHP to memcached) without any other special firewall rules.
But, until very recently memcached had no built-in access control, and even if present it's typically off by default, so anybody who can reach it on port 11211 can read or write anything to the cache. Definitely not what you want! Thus the firewall port needs to stay closed.


text:
Q: How to calculate the geometric moments of a log-normal distribution? If I only know geometric mean and geometric standard deviation of a log-normal distribution how can I calculate the $n$-th moment of the distribution?
In the Wikipedia article I can only see a relationship for the $n$-th moment if the (arithmetic) mean and standard deviation are known:
$$
E\left[X^n\right]=e^{n\mu+\frac{1}{2}n^2\sigma^2}
$$
If only the geometric mean and geometric standard deviation are known, is there still a way to calculate the moments?
The geometric mean and standard deviation are defined by:
$$
GM = e^{\mu_l}\quad\mathrm{where}\quad\mu_l = \frac{\sum_{i=1}^N\ln(x_i)}{N}
$$
and
$$
GSD = e^{\sigma_l}\quad\mathrm{where}\quad\sigma_l=\sqrt{\frac{\sum_{i=1}^N\left[\ln(x_i)-\mu_l\right]^2}{N}}
$$

A: For simplicity I will call $\mathcal{N}_k$ the $k$-th moment of the normal distribution with parameters $\mu$ and $\sigma$, so for example $\mathcal{N}_1 = \mu$, $\mathcal{N}_2 = \mu^2 + \sigma^2$, $\cdots$
Now if $X$ follows a lognormal distribution, then
\begin{eqnarray}
\mathbb{E}[\ln^k X] &=& \int\frac{{\rm d}x~}{x}\frac{\ln^k x}{\sigma\sqrt{2\pi}} \exp\left[-\left(\frac{\ln x - \mu}{2\sigma^2}\right)^2\right] \\
&\stackrel{y=\ln x}{=}&\int{\rm d}y ~\frac{y^k}{\sigma\sqrt{2\pi}}\exp\left[-\left(\frac{y-\mu}{2\sigma^2}\right)^2 \right] \\
&=& \mathcal{N}_k \tag{1}
\end{eqnarray}
In you case, you have then
$$
\mu_l = \ln{\rm GM} = \mathbb{E}[\ln X] = \mathcal{N}_1 = \mu
$$
and
$$
\sigma_l^2 = \mathbb{E}[(\ln X - \mu_l)^2] = (\cdots) = \sigma^2
$$
$\mu_l$ and $\sigma_l$ thus allow you to estimate $\mu$ and $\sigma$


text:
Q: Can anyone explain why listAdapter does not take a generic argument? I looked on http://developer.android.com/reference/android/widget/ListAdapter.html and saw that ListAdapter is a pubic interface. From that i know ArrayAdaptor implements ListAdaptor. To create an instance of ArrayAdaptor of reference type ListAdaptor, my code was:
ListAdapter adaptor = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1);

(this compiled fine).
My question is why is why ListAdapter does not take any generic arguments?
I tried comparing this to creating an array list with List (a public interface) reference. To do this my code was:
 List<String> l = new ArrayList<String>();

Can anyone explain the differenes between initialization process of the two?
List seems more intuitive, since if the parent is generic, the child should be too.

A: ArrayAdapter<T> implements ListAdapter. This means that it abides by the contract of ListAdapter. In this case this simply means that it implements the methods areAllItemsEnabled() and isEnabled(int position).
There is no reason that ListAdapter should take a generic type, because these two methods don't involve the generic type.

A: What do you mean by not generic?  The interface is a very generic one-  it can be an interface to any type of data.  It doesn't even force you to a particular data structure for that data, like an array or a cursor.
Do you mean why doesn't it take a generic argument?  Because ListAdapter is actually more generic than that-  it doesn't care what type of data is in your list, so it doesn't require the generic type.  Notice that none of its functions requires it to know the type of the data.  While List does because it provides a bunch of functions that require you to know the type, such as add and remove.


text:
Q: Trying to recreate BiLSTM model from Adhikari et al. 2019 (LSTM_reg) in Tensorflow Im trying to recreate this model LSTM_reg from this paper in TensorFlow to use in my problem. I've come up with the following code:
def get_model(lr=0.001):
    model = tf.keras.models.Sequential()
    model.add(tf.keras.layers.Embedding(nb_words, output_dim=embed_size, weights=[embedding_matrix], input_length = maxlen, trainable=False))
    model.add(tf.keras.layers.Dropout(0.2)) # embedding dropouts
    model.add(tf.keras.layers.Bidirectional(tf.keras.layers.LSTM(256, return_sequences=True, recurrent_dropout=0.2, activation = 'tanh'))) # weight drop on recurrent layers using recurrent_dropout
    model.add(tf.keras.layers.MaxPooling1D(pool_size=2, padding = 'valid'))
    model.add(tf.keras.layers.Flatten())
    model.add(tf.keras.layers.Dense(512, activation='relu'))
    model.add(tf.keras.layers.Dropout(0.5))
    model.add(tf.keras.layers.Dense(20))
    model.add(tf.keras.layers.Activation('sigmoid'))

    model.compile(loss = 'categorical_crossentropy' , optimizer = 'adam', metrics = ['accuracy', tfa.metrics.F1Score(num_classes = 20)])
    return model

Have I gone about this the right way? Got some pretty weird values while training my dataset, hence was wondering about my implementation.. There is a pytorch implementation for this model here. But I'm not sure if I have reproduced this correctly.

A: One major difference I can see is that the paper uses a global max pooling, whereas you've only used max pooling with a kernel size of 2:
def get_model(lr=0.001):
    model = tf.keras.models.Sequential()
    model.add(tf.keras.layers.Embedding(nb_words, output_dim=embed_size, weights=[embedding_matrix], input_length = maxlen, trainable=False))
    model.add(tf.keras.layers.Dropout(0.2)) # embedding dropouts
    model.add(tf.keras.layers.Bidirectional(tf.keras.layers.LSTM(256, return_sequences=True, recurrent_dropout=0.2, activation = 'tanh'))) # weight drop on recurrent layers using recurrent_dropout
    model.add(tf.keras.layers.GlobalMaxPooling1D())
    model.add(tf.keras.layers.Dense(512, activation='relu'))
    model.add(tf.keras.layers.Dropout(0.5))
    model.add(tf.keras.layers.Dense(20))
    model.add(tf.keras.layers.Activation('sigmoid'))

    model.compile(loss = 'categorical_crossentropy' , optimizer = 'adam', metrics = ['accuracy', tfa.metrics.F1Score(num_classes = 20)])
    return model

I obviously don't have your data so make sure that the arguments are set correctly: https://keras.io/api/layers/pooling_layers/global_max_pooling1d/.
Another change is that the pytorch repo you shared has a ReLU after the LSTM (I don't know why). You could try adding that in and see if it helps.


text:
Q: SQL server 2008R2 The transaction log for database 'MGR' is full due to 'ACTIVE_TRANSACTION' I run a query in which I wanted to update more then 130 mln of records. After few hours I got an error:
The transaction log for database 'MGR' is full due to 'ACTIVE_TRANSACTION'.
now I ve got 70 MB free on my C disk drive.
I supose that the problem was with to little disc space and thats why query failed but how can I now regain the lost disc space from before query ?
Im using sql server 2008 R2
Thanks for any hints

A: The problem has to do with how sql logs all the changes during an active transaction. While a transaction is active, the log cannot be flushed, so if you have a huge active transaction the log keeps growing until it reaches a point where it can exceed its capacity. The amount of logging depends on many factors: the recovery mode (full recovery mode is the one that generates more logging activity). Also, you can breakdown the transaction in small chunks to enable log flushing in between. Also look into table hint TABLOCK. The lost amount of disk must possibly have gone to the log file. Check that out.


text:
Q: How to avoid Duration from pop up in gantt chart Google chart I have a Google Gantt chart and I need to avoid duration because in my start date and end date I need to remove some days.
How can I avoid duration from pop up in the Gantt chart?
google.charts.load('current', { 'packages': ['gantt'] });
        google.charts.setOnLoadCallback(draw_Charts);
        function draw_Charts() {
           $.ajax({
                type: "POST",
                url: "/web_service/Chart.asmx/Char,
                datadata: '{}',
                contentType: "application/json; charset=utf-8",
                dataType: "json",
                success: function (response) {
                    var dataTable = new google.visualization.DataTable();
                    dataTable.addColumn('string', 'Task ID');
                    dataTable.addColumn('string', 'Name');
                    dataTable.addColumn('string', 'Resources');
                    dataTable.addColumn('date', 'Start');
                    dataTable.addColumn('date', 'End');
                    dataTable.addColumn('number', 'Duration');
                    dataTable.addColumn('number', 'Percent Complete');
                    dataTable.addColumn('string', 'Dependencies');

                    for (var i = 0; i < response.d.length; i++) {
                        var Task_ID = response.d[i][1];
                        var name = response.d[i][1];
                        var Resources = null;
                        var start = new Date(response.d[i][2].toString());
                        var end = new Date(response.d[i][3].toString());
                        var Duration = null;
                        var Percent = null;
                        var Dependencies = null;
                        dataTable.addRows([[Task_ID, name, Resources, start, end, Duration, Percent, Dependencies]]);
                    }
                    var paddingHeight = 30;
                    var rowHeight = dataTable.getNumberOfRows() * 35;
                    var chartHeight = rowHeight + paddingHeight;
                    var options = {
                        width: "100%",
                        height: chartHeight,
                        gantt: {
                            trackHeight: 30, // Critical path arrows will be the same as other arrows.

                            arrow: {
                                angle: 100,
                                width: 5,
                                color: 'green',
                                radius: 0
                            },
                            barCornerRadius: 2,
                            backgroundColor: {
                                fill: 'transparent',
                            },
                            shadowOffset: 2,
                            palette: [
                                {
                                    "color": "#ff5d00",
                                    "dark": "#FCD6B6",
                                    "light": "#eeeeee"
                                }
                            ]
                        }
                    };
                    var container = document.getElementById('chart_div');
                    var chart = new google.visualization.Gantt(container);
                    chart.draw(dataTable, options);
                },
                failure: function (r) {
                    alert(r.status + " - " + r.statusText);
                },
                error: function (r) {
                    alert(r.status + " - " + r.statusText);
                }
            });
        }


text:
Q: Adding elements to List using a comprehension Lets say I have a list:
List = [1,2,3,4,5]

I want to use a comprehension to output a list of lists for every element, let's say i, in "List" containing 1,2,...,i.  So the comprehension would output:
[[1],[1,2],[1,2,3],[1,2,3,4],[1,2,3,4,5]]

The same would work for a List of List = [1,3,5] where the output would be:
[[1],[1,2,3],[1,2,3,4,5]

I do not want to use any modules like numpy or itertools
Any help would me much appreciated!

A: Sure:
>>> [range(1, i+1) for i in List]
[[1], [1, 2], [1, 2, 3], [1, 2, 3, 4], [1, 2, 3, 4, 5]]


text:
Q: How to load an initial value for a ClearableFileInput / FileField (before form is bound) How do I set an initial value for a FileField that will display in a ClearableFileInput widget when creating a new object (unbound form)?
I have tried the following but widget.value does not return a FeildFile instance if it is the first time the user is creating the object:
models.py
class MyModel(models.Model):
    myfile=models.FileField()

forms.py
class MyForm(forms.ModelForm):

    def __init__(self, *args, **kwargs):
        super(MyForm, self).__init__(*args, **kwargs)
        self.fields['myfile'].initial= 'myfile.pdf'

    class Meta:
        model = Issuer
        fields = ['myfile']

This results in :

Similarly, setting a default value in the modelfield does not work:
class MyModel(models.Model):
    myfile=models.FileField(default='myfile.pdf')

The widget initial value is still None, but if it is left empty and saved the file object myfile.pdf will be created. The settings.MEDIA_URL and urls.py is definitely correct and the file is on the system because it is loaded after form save.
What I am missing is showing it as an initial value before a form is saved and an object created.
This answer suggests you can't provide initial data but you can provide an initial value with a url attribute to fake the appearance of a file. It's not clear how you would do this though.
Trying to create an initial file object in the form also returns widget.value = None
class MyForm(forms.ModelForm):

    f_path = os.path.join(settings.BASE_DIR + settings.MEDIA_URL, 'myfile.pdf')

    f = open(f_path)
    myfile = File(f)

    def __init__(self, *args, **kwargs):
        super(MyForm, self).__init__(*args, **kwargs)
        self.fields['privacy_policy'].initial = self.myfile

A: Your last block of code is quite close.
You are actually telling the user through the ClearableFileInput widget that if the user does not input anything in the file input, the initial value will be your pdf file.
But, this is only for display, you have to actually put the logic when you save the instance! (FileField won't do it for you) So the right thing is to override the save() method of your form, and in the case of a creation, put the actual file as the value. Like this:
class MyForm(forms.ModelForm):
    def __init__(self, *args, **kwargs):
        path = os.path.join(settings.MEDIA_ROOT, 'myfile.pdf')

        self.default_file = open(path)

        super(MyForm, self).__init__(*args, **kwargs)
        self.fields['privacy_policy'].initial = File(self.default_file)
        self.fields['privacy_policy'].initial.url = default_storage.url('myfile.pdf')

    def save(self, commit=True):
        # Actually put the default file as a value if no input for creation
        if not self.instance.pk and not self.cleaned_data.get('privacy_policy'):
            self.instance.privacy_policy = self.default_file
            self.instance.privacy_policy._committed = True
        super().save(commit)

A: You can't.
The only way to set the value of a file input is by the user to select it.
This is done for security reasons. Otherwise, you would be able to create a Javascript that automatically uploads a specific file from the client's computer.
it has nothing to with Django (model, form) its a browser feature, we only do the things with Django form if it is possible in Html and javascript.
your form:
class MyForm(forms.ModelForm):

f_path = os.path.join(settings.BASE_DIR + settings.MEDIA_URL, 'myfile.pdf')

f = open(f_path)
myfile = File(f)

def __init__(self, *args, **kwargs):
    super(MyForm, self).__init__(*args, **kwargs)
    self.fields['privacy_policy'].value = self.myfile

the default ClearableFileField template is
{% if widget.is_initial %}{{ widget.initial_text }}: {{ widget.value }}{% if not widget.required %}
<input type="checkbox" name="{{ widget.checkbox_name }}" id="{{ widget.checkbox_id }}">
{{ widget.clear_checkbox_label }}{% endif %}

{{ widget.input_text }}:{% endif %}
<input type="{{ widget.type }}" name="{{ widget.name }}"{% include "django/forms/widgets/attrs.html" %}>

The widget is_initial should be true to see the link.
class ClearableFileInput(FileInput):
    ...

    def is_initial(self, value):
        """
        Return whether value is considered to be initial value.
        """
        return bool(value and getattr(value, 'url', False))

     ....

A: I have managed set a ClearableFileInput by creating a model with the custom url and then setting specifying that model as the instance.
In your example it would be something like this (untested):
model = MyModel(myfile='abc.txt')
form = MyForm(instance=model)

However, I have found that if you have FILES included in the form (i.e.: MyForm(request.POST, request.FILES, instance=model)` the FILES takes precedence.
I have found this very finicky, so hope this helps.

A: From Django Documentation
FileField.upload_to
This attribute provides a way of setting the upload directory and file name, and can be set in two ways. In both cases, the value is passed to the Storage.save() method.
If you specify a string value or a Path, it may contain strftime() formatting, which will be replaced by the date/time of the file upload (so that uploaded files don't fill up the given directory). For example:
class MyModel(models.Model):
    # file will be uploaded to MEDIA_ROOT/uploads
    upload = models.FileField(upload_to='uploads/')
    # or...
    # file will be saved to MEDIA_ROOT/uploads/2015/01/30
    upload = models.FileField(upload_to='uploads/%Y/%m/%d/')

For example, say your MEDIA_ROOT is set to '/home/media', and upload_to is set to 'photos/%Y/%m/%d'. The '%Y/%m/%d' part of upload_to is strftime() formatting; '%Y' is the four-digit year, '%m' is the two-digit month and '%d' is the two-digit day. If you upload a file on Jan. 15, 2007, it will be saved in the directory /home/media/photos/2007/01/15.


text:
Q: Deleting every point older than the most recent one of each unique ID What I'm trying to achieve is to only keep the latest of any given point identified by an ID, delete everything else.
The ID is a tag.
So let's say we have:
time                 ID   ...
2022-06-28 18:29:00  id1  ...
2022-06-28 18:28:00  id1  ...
2022-06-28 18:27:00  id1  ...
2022-06-28 18:29:00  id2  ...
2022-06-28 18:28:00  id2  ...
2022-06-28 18:29:00  id3  ...

Would result to:
time                 ID   ...
2022-06-28 18:29:00  id1  ...
2022-06-28 18:29:00  id2  ...
2022-06-28 18:29:00  id3  ...

Is that possible without having to do something like:
DELETE FROM "measurement" WHERE "ID" = '...' AND time < ...

Which take way too much time to execute on all possible "duplicates". You can't also have any OR in a delete where statement. Multiple statements like specified here also take too long to execute.

A: Having ID as a tags has saved you a lot of time already.
Maybe we could think over a little bit about your scenario. Are you trying to keep the LATEST data for every INTERVAL? For example, your original sampling rate is 1 second (that is, your data is fed into the InfluxDB every single second) and you would like downsample it for every 5 seconds. That is, you are only taking the last record over that 5-second interval and dump all rest of data.
If the above assumption is right, you could try:

*

*run continuous queries first to get your downsampled data into another database per this doc:

CREATE CONTINUOUS QUERY "cq_basic" ON "someDatabase"
BEGIN
  SELECT time, id, LAST("fieldA"), LAST("fieldA") INTO "latest_5sec_measurement" FROM "measurement" GROUP BY time(5s)
END

This CQ is like a cron job and will keep transforming the original data into the less granular one.

*delete the obsolete data with time range (InfluxDB loves you when you are doing this as time range deletion is the most efficient way) in the original database per this doc:

DELETE WHERE time > '2022-06-27 18:29:00' AND time < '2022-06-28 18:29:00'

And you can set up another cron job to run this query as long as you double check the above CQ has been executed successfully.


text:
Q: function with get / http / subscribe dont worked, why? This function with get / http / subscribe does not return the correct value, it returns undefined, why?`
function_one() {
    let text = this.getData();
    console.log(' Here text is undefined --> ', text);
  }

  getData() {
    this.http.get("assets/img/tutorial/tutorialenus.JSON").subscribe
      (response => {
        console.log(' Here response = The simple text', response);
        return response;
      }
      );
  }

A: You'll need to return your observable and subscribe to it in order to get the value.
Try this:
function_one() {
    this.getData().subscribe((text) => {
        // Do something with text
        console.log('Your text will appear', text);
    });

}

getData() {
    return this.http.get("assets/img/tutorial/tutorialenus.JSON");
}

A: without seeing the rest of the code: I would recommend this:
getData() {
  //return observable
  return this.http.get("assets/img/tutorial/tutorialenus.JSON");
}

function_one() {
  //subscribe to and log observable response data
  this.getData().subscribe
  (response => {
    console.log(' Here response = The simple text', response);
  }
}

A: The HTTP get function is asynchronous. So it wont return data to function_one(). To fix this, instead of having function_one() call getData(), have getData() call function_one().
Like this
  function_one(text) {
    console.log(' Here text is undefined --> ', text);
  }

  getData() {
    this.http.get("assets/img/tutorial/tutorialenus.JSON").subscribe
      (response => {
        console.log(' Here response = The simple text', response);
        this.function_one(response)
      });
  }


text:
Q: Reviews/Comparison of Open Source ASP.NET MVC CMS I am looking for an open source CMS for ASP.NET MVC.  I have found MvcCms, N2, and AtomicCMS.  I'm looking for any advice, anecdotes, resources or articles comparing the different open source projects so I can find the best one for my project.  I'd like to find information about the features, extensibility, relative reliability and continued development of the different projects.  Thanks guys.

A: You ought to look at Orchard CMS.  It was released a few days ago, so still in its infancy.  We are having a very close look as most clients want this kind of thing.
Orchard is open source, but it is part of Microsoft's push for MVC 3.  So there are a lot of very good brains behind it.
On the other hand, there is a rule whereby you only take an MS product seriously when version 3 comes out.  What I think you will find is that they will rattle out the versions quite quickly, so I would bet on this one.
To date, we use Telerik Sitefinity for all CMS.  The pros are that it uses master pages, so no new skills.  The cons, it is slow and I have found it tedious to customise.
Still, it delivers good websites.  For example, one we did (still under development):
Preston Reid Travel Agency
It is entirely updated by the staff who definitely NOT technically minded.
However, Sitefinity is not MVC, so I will get increasingly out of date with it, plus you have to pay for commercial sites (from US$ 499).
Orchard is free and will get a big community eco system, so will evolve quickly.  I suspect Orchard will kill off all the other free MVC CMS.
That's my bet, and it has always paid to bet on Microsoft...

A: I can find a few listed and compared here; have a look. Hope it helps.


text:
Q: anyone can explain the "field of view" In graphics software, sometimes we saw "field of view" for camera. Can someone explain what does it mean?

A: The field of view (in the gluPerspective call) is the angle in degrees between a plane which passes through the camera position and the top of your screen and another plane which passes through the camera position and the bottom of your screen.
Edit:
Since you need not have a full-screen viewport: Any line which is projected to (x1, 0)-(x2, 0) lies in the first plane, any line that is projected to (x3, height)-(x4, height) lies in the second, where height is the height of your viewport in pixels.

A: The field of view is normally the horizontal field of view.
This is the angular extent of the observable world Wikipedia
The larger the field of view the more of the scene you can see, but each bit will be seen at a lower resolution.
The vertical field of view is related to the horizontal by the aspect ratio of the view. A square view will have the same horizontal and vertical FoV. A landscape view will have a smaller vertical FoV while a portrait view will have a larger vertical FoV.


text:
Q: How to create telerik mvc windows programmatically There is a command like this that I'm using:
var windowElement = $.telerik.window.create({
title: "Insert image",
html: "Inserting an image...",
contentUrl: '',
modal: true,
resizable: false,
draggable: true,
scrollable: false,
onClose: function() {}

});
But this give me an error saying that $.telerik.window is undefined.

A: In order for the Telerik javascript files to be loaded you will need to include the Telerik ScriptRegistrar at the end of your master page.
Checkout the following article: Telerik Extensions for ASP.NET MVC Manual
Looking specifically at the following section:

The ScriptRegistrar should be placed after all components on the page.
  Typically you could put the ScriptRegistrar component at the end of
  the master page.

The ScriptRegistrar searches for the Telerik javascript files in certain locations:

The ScriptRegistrar component looks for JavaScript files in the
  following order:
First it will search for a folder with the same name
  as the version of the Telerik.Web.Mvc.dll assembly located in the
  Scripts folder of your    ASP.NET MVC application. If such a folder is
  found the ScriptRegistrar will look for the following extensions:
*.debug.js
*.min.js
*.js
If there is no such folder, the ScriptRegistrar will search in
  the Scripts folder of the ASP.NET MVC application. It is better to
  copy the folder with the version for easier upgrade.

Hope this helps.


text:
Q: Why need grammar in Speech Recognition C# SpeechRecognitionEngine sre = new SpeechRecognitionEngine();
Choices clist = new Choices();
// just assume I have added words in clist not shown here
Grammar gr = new Grammar(new GrammarBuilder(clist));

sre.RequestRecognizerUpdate();
sre.LoadGrammar(gr);
sre.SpeechRecognized += sre_SpeechRecognized;
sre.SetInputToDefaultAudioDevice();
sre.RecognizeAsync(RecognizeMode.Multiple);

 void sre_SpeechRecognized(object sender, SpeechRecognizedEventArgs e)
 {
//This only outputs words present in grammar
   Console.WriteLine(e.Result.Text);
 }

In short why do we need a grammar in speech recognition. Whats the point if a grammar is needed. If the recognizer has to match strings present in grammar, why can't we just output what the speech recognizer recognized without grammar?
Thanks and kindly correct me where i'm wrong.

A: We use grammar to make difference in context for rhyming words or how the word was pronounced. Example hello and yellow. There is a nice explanation with sample at the link. Hello relates to greetings grammar while yellow relates to color grammar. This improves efficiency/accuracy of recognition.

If the grouping inside of grammar rules or grammars are clever,
  developers can enable and disable scenarios when the system moves into
  a specific state.  It can give context and, in some cases, better
  accuracy for the words the system is listening for.

You can also refer MSDN link to understand the detail on the Purpose of Grammars.
It helps code to provide functionalities like Limits Vocabulary, Customizes Vocabulary, Filters Recognition Results and Identifies Rules.


text:
Q: CSS: Why can not use img:hover to show drop-down menu I want to perform an action that when I hover on the image, the drop-down menu will be shown.
The below code works fine.
HTML, CSS:

.menu {
  position: relative;
  display: inline-block;
}
.menu .dropdown-menu {
  position: absolute;
  top: 100%;
  left: 0;
  margin: 0;
  display: none;
}
.menu:hover .dropdown-menu {
  display: block;
}

Account

My question is why I can't use #menu-icon:hover to perform the action?
#menu-icon:hover .dropdown-menu {
    display:block;
}

A: Based on this structure:

Account

The selector / combinator you are using is incorrect and should be:
#menu-icon:hover + .dropdown-menu {
display:block;
}

The space between .menu-icon and .dropdown-menu you are using assumes that the menu is a child of the image which it isn't.
The menu is the next sibling and is selected with the + combinator.
The 30 CSS Selectors You Must Memorize

A: Just like to add that using hover as the only way to show a menu is not very user-friendly. If you are not using a mouse it's not possible to interact with the menu. Also even if you are using a mouse it can be hard to interact since the menu will close as soon as the mouse is not actually hovering.
I would suggest trying something else or maybe add some JavaScript to improve the accessibility.


text:
Q: Check if a file is a specific type in C I'm writing my first C program, though I come from a C++ background.
I need to iterate through a directory of files and check to see if the file is a header file, and then return the count.
My code is as follows, it's pretty rudimentary I think:
static int CountHeaders( const char* dirname ) {

    int header_count = 0;
    DIR* dir_ptr;
    struct dirent* entry;

    dir_ptr = opendir( dirname );

    while( ( entry = readdir( dir_ptr ) ) )
    {
        if ( entry->d_type == DT_REG )
        {
            //second if statement to verify the file is a header file should be???
            ++header_count;
        }
    }

    closedir( dir_ptr );

    return header_count;
}

What would be a good if statement to check to see if the file is a header?

A: Simply check if the file extension is .h, something like:
const char *ext = strrchr (entry->d_name, '.');
if ((ext != NULL) && (!strcmp (ext+1, "h"))) {
     // header file
}

Ofcourse, note that this assumes all your header files have an .h extension, which may or may not be true, the C standard does not mandate that header files must have an .h extension.

A: Each dirent structure has a d_name containing the name of the file, so I'd be looking to see if that followed some pattern, like ending in .h or .hpp.
That would be code along the lines of:
int len = strlen (entry->d_name);
if ((len >= 2) && strcmp (&(entry->d_name[len - 2]), ".h") == 0))
    header_count++;
if ((len >= 4) && strcmp (&(entry->d_name[len - 4]), ".hpp") == 0))
    header_count++;

Of course, that won't catch truly evil people from calling their executables ha_ha_fooled_you.hpp but thanfkfully they're in the minority.
You may even want to consider an endsWith() function to make your life easier:
int endsWith (char *str, char *end) {
    size_t slen = strlen (str);
    size_t elen = strlen (end);
    if (slen < elen)
        return 0;
    return (strcmp (&(str[slen-elen]), end) == 0);
}
:
if (endsWith (entry->d_name, ".h"))   header_count++;
if (endsWith (entry->d_name, ".hpp")) header_count++;

A: There are some much better methods than checking the file extension.
Wikipedia has a good article here and here. The latter idea is called the magic number database which essentially means that if a file contains blah sequence then it is the matching type listed in the database. Sometimes the number has restrictions on locations and sometimes it doesnt. This method IMO is more accurate albeit slower than file extension detection.
But then again, for something as simple as checking to see if its a header, this may be a bit of overkill XD

A: You could check if the last few characters are one of the header-file extensions, .h, .hpp, etc. Use the dirent struct's d_name for the name of the file.
Or, you could run the 'file' command and parse its result.

A: You probably just want to check the file extension. Using dirent, you would want to look at d_name.

A: That's up to you.
The easiest way is to just look at the filename (d_name), and check whether it ends with something like ".h" or ".hpp" or whatever.
Opening the file and actually reading it to see if it's valid c/c++, on the other hand, will be A LOT more complex... you could run it through a compiler, but not every header works on its own, so that test will give you a lot of false negatives.


text:
Q: EclipseLink JPA re-orders column-names in INSERT statement and causes exceptions I am using the latest version of PostgreSQL and postgresql-9.4.1208.jar (JDBC library).

*

*using glassfish 4.1

*EclipseLink Eclipse Persistence Services - 2.6.2.v20151217-774c696

Need assistance to FORCE the order of the column-names in the INSERT SQL autogenerated by JPA.
The INSERT SQL (automatically created by entityMgr.persist(...));
Note: the ordering of columns is so wacky, but the values are EXACTLY as I have in the java source (I even prefixed the columns with "order#" to track).
Exception [EclipseLink-4002] (Eclipse Persistence Services - 2.6.2.v20151217-774c696): org.eclipse.persistence.exceptions.DatabaseException
Internal Exception: org.postgresql.util.PSQLException:
ERROR: column "c08_cancel_dt" is of type timestamp with time zone but expression is of type character varying
    Hint: You will need to rewrite or cast the expression.
    Position: 211
    Error Code: 0
    Call: INSERT INTO apns_new_request (c01_seqnum, c03_app_on_device,
    c08_cancel_dt, c02_device_id, c07_due_dt, c05_item_id,
    c11_item_title, c10_modified, c09_received, c06_request_state,
    c04_event_src)
    VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
        bind => [11 parameters bound]
    Query: InsertObjectQuery(
    afjkalkhawifualjfklsdjkczsd,        <<-- c02_
    iOS-Calendar-zzzzzzzzzzzzzzzzzz,    <<-- c03_
    LaptopBrowser,                      <<-- c04_
    123000123,                          <<-- c05_
    1,2016-05-06T20:51:44.662-04:00,    <<-- c06_
    null,                               <<-- c07_
    2016-05-05T20:51:44.662-04:00,      <<-- c08_
    2016-05-05T20:51:44.662-04:00,      <<-- c09_
    Hi-OffsetDateTime-1!)               <<-- c10_

Not an issue, but Notice the same wacky-ordering below, during TABLE-CREATE, how the column-names prefixed to force ordering fails... during deployment (persistence.xml has 'drop-and-create-tables')
 org.eclipse.persistence.session./file:/opt/glassfish4/glassfish/domains/domain1/applications/iOS_RemoteNotif/WEB-INF/classes/_APNSPersistenceUnit.sql] [tid: _ThreadID=46 _ThreadName=admin-listener(5)] [timeMillis: 1462495579354] [levelValue: 500] [[
    CREATE TABLE apns_new_request (c01_seqnum  BIGINT NOT NULL , c03_app_on_device  CHAR(32) NOT NULL ,
    c08_cancel_dt  TIMESTAMP WITH TIME ZONE NULL , c02_device_id  VARCHAR(128) NOT NULL ,
    c07_due_dt  TIMESTAMP WITH TIME ZONE NOT NULL , c05_item_id  CHAR(32) NOT NULL ,
    c11_item_title  VARCHAR(64) NOT NULL , c10_modified  TIMESTAMP WITH TIME ZONE NOT NULL ,
    c09_received  TIMESTAMP WITH TIME ZONE NOT NULL , c06_request_state  SMALLINT NOT NULL ,
    c04_event_src  CHAR(64) NOT NULL , PRIMARY KEY (c01_seqnum))]]

A: The InsertObjectQuery is just calling toString on the object it is inserting, and is NOT showing the parameters bound to the statement.  Parameters would be shown within the "[11 parameters bound]" of the log, if you have enabled parameter binding
Show the mapping for the c08_cancel_dt field to see why it might be having issues, as well as the parameters being used for it in the query.

A: EclipseLink Bug (when influenced by custom @annotations - which causes column positioning mismatch for auto-generated INSERT SQL)
Eclipse Persistence Services - 2.6.2.v20151217-774c696
Very simple proof.
I replaced all java.time.OffsetDateTime with java.util.Date - for all date fields in the Entity Bean.
I got rid of my @CustomBeanValidator annotations from that bean.
Then I deleted (my own) Custom Bean-Validator java files (MyOffsetDateTimeValidator & OffsetDateTimeValidator),
as well as the Custom JPA-field-converter java class (JPAOffsetDateConverter).
See My other post that contains the code for these two java classes
mvn clean package deploy ....
Now JPA Works like a charm - no errors and no warnings in the GlassFish logs.
Data is stored perfectly in appropriate columns in the PostgreSQL tables!
P.S: Unfortunately, I still do not have timezone data in the database, so will have to use workarounds/ additional entity-bean fields...


text:
Q: A reshape puzzle in data.table Yet another reshape problem in data.table
set.seed(1234)
DT <- data.table(x=rep(c(1,2,3),each=4), y=c("A","B"), v=sample(1:100,12))
#    x y  v
# 1: 1 A 12
# 2: 1 B 62
...
#11: 3 A 63
#12: 3 B 49

I would like to do a cumulative sum of x and v by y but the result to be presented as:
The number of lines always stays the same, and when y==A the SUM.*.A is incremented, same when y==B. (As usual y could have many factors, 2 in this example)
#     SUM.x.A SUM.x.B  SUM.v.A SUM.v.B
# 1:        1      NA       12      NA
# 2:        1       1       12      62
...
#11:       12       9       318     289
#12:       12      12       318     338

EDIT: Here is my poor solution clearly overly complicated
#first step is to create cumsum columns
colNames <- c("x","v"); newColNames <- paste0("SUM.",colNames)
DT[, newColNames:=lapply(.SD,cumsum) ,by=y, .SDcols=colNames, with=F];
#now we need to reshape each SUM.* to SUM.*.{yvalue}
DT[,N:=.I]; setattr(DT,"sorted","N")

g <- function(DT,SD){
  cols <- c('N',grep('SUM',colnames(SD), value=T));
  Yval <- unique(SD[,y]);
  merge(DT, SD[,cols, with=F], suffixe=c('',paste0('.',Yval)), all.x=T);
}

DT <- Reduce(f=g,init=DT,x=split(DT,DT$y));

locf = function(x) {
  ind = which(!is.na(x))
  if(is.na(x[1])) ind = c(1,ind)
  rep(x[ind], times = diff( c(ind, length(x) + 1) ))
}

newColNames <- grep('SUM',colnames(DT),value=T);
DT <- DT[, (newColNames):=lapply(.SD, locf), .SDcols=newColNames]

A: Try this:
cumsum0 <- function(x) { x <- cumsum(x); ifelse(x == 0, NA, x) }
DT2 <- DT[, {SUM.<-y; lapply(data.table(model.matrix(~ SUM.:x + SUM.:v + 0)), cumsum0)}]
setnames(DT2, sub("(.):(.)", "\\2.\\1", names(DT2)))

Simplifications:
1) If using 0 in place of NA is ok then it can be simplified by omitting the first line which defines cumsum0 and replacing cumsum0 in the next line with cumsum.
2) The result of the second line has these names:
> names(DT2)
[1] "SUM.A:x" "SUM.B:x" "SUM.A:v" "SUM.B:v"

so if that is sufficient the last line can be dropped since its only purpose is to make the names exactly the same as in the question.
The result (without the simplifications) is:
> DT2
    SUM.x.A SUM.x.B SUM.v.A SUM.v.B
 1:       1      NA      12      NA
 2:       1       1      12      62
 3:       2       1      72      62
 4:       2       2      72     123
 5:       4       2     155     123
 6:       4       4     155     220
 7:       6       4     156     220
 8:       6       6     156     242
 9:       9       6     255     242
10:       9       9     255     289
11:      12       9     318     289
12:      12      12     318     338

A: Here's another way:
ys <- unique(DT$y)
sdcols <- c("x", "v")
cols <- paste0("SUM.", sdcols)
DT[, c(cols) := lapply(.SD, cumsum), by = y, .SDcols = sdcols]
for( i in seq_along(ys)) {
    cols <- paste0("SUM.", sdcols, ".", ys[i])
    DT[, c("v1", "v2") := list(SUM.x, SUM.v[i]), by = SUM.x]
    DT[, c("v1", "v2") := list(c(rep(NA_integer_, (i-1)), v1)[seq_len(.N)],
    c(rep(NA_integer_, (i-1)), v2)[seq_len(.N)])]
    setnames(DT, c("v1", "v2"), cols)
}

My version of benchmarking with mnel's (from his post) and this function:
The function from this post:
arun <- function(DT) {

    ys <- unique(DT$y)
    sdcols <- c("x", "v")
    cols <- paste0("SUM.", sdcols)
    DT[, c(cols) := lapply(.SD, cumsum), by = y, .SDcols = sdcols]
    for( i in seq_along(ys)) {
        cols <- paste0("SUM.", sdcols, ".", ys[i])
        DT[, c("v1", "v2") := list(SUM.x, SUM.v[i]), by = SUM.x]
        DT[, c("v1", "v2") := list(c(rep(NA_integer_, (i-1)), v1)[seq_len(.N)],
        c(rep(NA_integer_, (i-1)), v2)[seq_len(.N)])]
        setnames(DT, c("v1", "v2"), cols)
    }
    DT
}

Function from mnel's post:
mnel <- function(DT) {
    set.seed(1234)
    DT <- data.table(x=rep(c(1,2,3),each=4), y=c("A","B"), v=sample(1:100,12))
    DT[, id := seq_len(nrow(DT))]
    setkey(DT, y)
    uniqY <- unique(DT$y)
    for(jj in uniqY){
      nc <- do.call(paste, c(expand.grid('Sum', c('x','v'),jj), sep ='.'))
      DT[.(jj), (nc) := list(cumsum(x), cumsum(v))]

    }
    setkey(DT, id)
    DT[, 5:8 := lapply(.SD, function(x) {
      xn <- is.na(x)
      x[xn] <- -Inf
      xx <- cummax(x)
      # deal with leading NA values
        if(xn[1]){
        xn1 <- which(xn)[1]
      xx[seq_len(xn1)] <- NA}
      xx }), .SDcols = 5:8]
}

Function from statquant:
statquant <- function(DT){
    #first step is to create cumsum columns
    colNames <- c("x","v")
    DT[, paste0("SUM.",colNames):=lapply(.SD,cumsum) ,by=y, .SDcols=colNames];
    #now we need to reshape each SUM.* to SUM.*.{yvalue}
    DT[,N:=.I]; setattr(DT,"sorted","N")

    g <- function(DT,SD){
      cols <- c('N',grep('SUM',colnames(SD), value=T));
      Yval <- unique(SD[,y]);
      merge(DT, SD[,cols, with=F], suffix=c('',paste0('.',Yval)), all.x=T);
    }

    DT <- Reduce(f=g,init=DT,x=split(DT,DT$y));

    locf = function(x) {
      ind = which(!is.na(x))
      if(is.na(x[1])) ind = c(1,ind)
      rep(x[ind], times = diff( c(ind, length(x) + 1) ))
    }

    newColNames <- grep('SUM',colnames(DT),value=T);
    DT <- DT[, (newColNames):=lapply(.SD, locf), .SDcols=newColNames]
    DT
}

Function from grothendieck
grothendieck <- function(DT) {
    cumsum0 <- function(x) { x <- cumsum(x); ifelse(x == 0, NA, x) }
    DT2 <- DT[, {SUM.<-y; lapply(data.table(model.matrix(~ SUM.:x + SUM.:v + 0)), cumsum0)}]
    setnames(DT2, sub("(.):(.)", "\\2.\\1", names(DT2)))
    DT2
}

Benchmarking:
library(data.table)
library(zoo)
set.seed(1234)
DT <- data.table(x=rep(c(1,2,3),each=4), y=c("A","B"), v=sample(1:100,12))

library(microbenchmark)
microbenchmark( s <- statquant(copy(DT)), g <- grothendieck(copy(DT)),
                m <- mnel(copy(DT)), a <- arun(copy(DT)), times = 1e3)

# Unit: milliseconds
#                         expr       min        lq    median        uq       max neval
#     s <- statquant(copy(DT)) 13.041125 13.674083 14.493870 17.273151 144.74186  1000
#  g <- grothendieck(copy(DT))  3.634120  3.859143  4.006085  4.443388  80.01984  1000
#          m <- mnel(copy(DT))  7.819286  8.234178  8.596090 10.423668  87.07668  1000
#          a <- arun(copy(DT))  6.925419  7.369286  7.703003  9.262719  53.39823  1000

resulting data.table "a" (arun's)
#     x y  v SUM.x SUM.v SUM.x.A SUM.v.A SUM.x.B SUM.v.B
#  1: 1 A 12     1    12       1      12      NA      NA
#  2: 1 B 62     1    62       1      12       1      62
#  3: 1 A 60     2    72       2      72       1      62
#  4: 1 B 61     2   123       2      72       2     123
#  5: 2 A 83     4   155       4     155       2     123
#  6: 2 B 97     4   220       4     155       4     220
#  7: 2 A  1     6   156       6     156       4     220
#  8: 2 B 22     6   242       6     156       6     242
#  9: 3 A 99     9   255       9     255       6     242
# 10: 3 B 47     9   289       9     255       9     289
# 11: 3 A 63    12   318      12     318       9     289
# 12: 3 B 49    12   338      12     318      12     338

Resulting data.table "m" (mnel's)
#    x y  v id Sum.x.A Sum.v.A Sum.x.B Sum.v.B
#  1: 1 A 12  1       1      12      NA      NA
#  2: 1 B 62  2       1      12       1      62
#  3: 1 A 60  3       2      72       1      62
#  4: 1 B 61  4       2      72       2     123
#  5: 2 A 83  5       4     155       2     123
#  6: 2 B 97  6       4     155       4     220
#  7: 2 A  1  7       6     156       4     220
#  8: 2 B 22  8       6     156       6     242
#  9: 3 A 99  9       9     255       6     242
# 10: 3 B 47 10       9     255       9     289
# 11: 3 A 63 11      12     318       9     289
# 12: 3 B 49 12      12     318      12     338

Resulting data.table "s" (statquant's)
#      N x y  v SUM.x SUM.v SUM.x.A SUM.v.A SUM.x.B SUM.v.B
#  1:  1 1 A 12     1    12       1      12      NA      NA
#  2:  2 1 B 62     1    62       1      12       1      62
#  3:  3 1 A 60     2    72       2      72       1      62
#  4:  4 1 B 61     2   123       2      72       2     123
#  5:  5 2 A 83     4   155       4     155       2     123
#  6:  6 2 B 97     4   220       4     155       4     220
#  7:  7 2 A  1     6   156       6     156       4     220
#  8:  8 2 B 22     6   242       6     156       6     242
#  9:  9 3 A 99     9   255       9     255       6     242
# 10: 10 3 B 47     9   289       9     255       9     289
# 11: 11 3 A 63    12   318      12     318       9     289
# 12: 12 3 B 49    12   338      12     318      12     338

Resulting data.table "g" (grothendieck's)
#    SUM.x.A SUM.x.B SUM.v.A SUM.v.B
#  1:       1      NA      12      NA
#  2:       1       1      12      62
#  3:       2       1      72      62
#  4:       2       2      72     123
#  5:       4       2     155     123
#  6:       4       4     155     220
#  7:       6       4     156     220
#  8:       6       6     156     242
#  9:       9       6     255     242
# 10:       9       9     255     289
# 11:      12       9     318     289
# 12:      12      12     318     338

A: Not sure this is the best solution, but you could do something like the following.
set.seed(1234)
DT <- data.table(x=rep(c(1,2,3),each=4), y=c("A","B"), v=sample(1:100,12))
DT[, id := seq_len(nrow(DT))]

setkey(DT, y)

uniqY <- unique(DT$y)

for(jj in uniqY){
  nc <- do.call(paste, c(expand.grid('Sum', c('x','v'),jj), sep ='.'))
  DT[.(jj), (nc) := list(cumsum(x), cumsum(v))]

}

setkey(DT, id)

DT[, 5:8 := lapply(.SD, function(x) {
  xn <- is.na(x)
  x[xn] <- -Inf
  xx <- cummax(x)
  # deal with leading NA values
    if(xn[1]){
    xn1 <- which(xn)[1]
  xx[seq_len(xn1)] <- NA}

  xx }), .SDcols = 5:8]


text:
Q: How does python assign id to a string? Consider the code below. Its output is
1 385712698864 385712698864
2 385744287024
3 385744287088
4 385712698864
5 385744286960
6 385744286960
7 385744286960
8 385712698864

This means that some of the operations in the code below change the id, but some do not, even though no operation changes the value of the variable a:

*

*setting the variable to the value "a" always results in the same id (in this particular run, that was 385712698864)

*using a.lower() changes the id of a after every call

*a[::-1] changes the id

*a[:1] does not change the id

*g(a) does not change the id

*f(a) changes the id

Can someone explain this seemingly inconsistent behaviour? (I am using python 3.8)
The code:
def f(x):
    y = x + x
    n = len(x)
    return y[:n]

def g(x):
    return "" + x

a = "a"
b = "a"
print(1, id(a), id(b))

a = a.lower()
print(2, id(a))

a = a.lower()
print(3, id(a))

a = "a"
print(4, id(a))

a = a[::-1]
print(5, id(a))

a = a[:1]
print(6, id(a))

a = g(a)
print(7, id(a))

a = f(a)
print(8, id(a))

A: Python strings are immutable, so (in general) any operations performed on a string return a new string. As an implementation detail of CPython (the standard Python implementation), id(x) usually returns the memory address of x. Sometimes it's trivially easy for the Python interpreter to recognise where it can re-use an existing string and save some memory (this is called 'interning', and is discussed in the context of other immutable types in Python in this SO answer), and in these cases 'both' strings will have the same id.
Take the assignment of an equal string to two different variables, for instance. The interpreter is clever enough to cache the literal string values (i.e. the token "a") and use the same string in memory to represent these. This is fine because you can't mutate strings anyway, and there's no danger of doing something astonishing.
You see this interning in example 1 and example 4: because the interpreter has already cached "a", these are given the same ID:
a = "a" * 20
b = "a" * 20
assert id(a) == id(b)  # True

With a longer string though, this behaviour doesn't happen:
a = "a" * 10_000
b = "a" * 10_000
assert id(a) == id(b)  # raises AssertionError

This also doesn't happen if you use a variable to change the length of the string, because it's less obvious to the parser that these would result in the same string:
>>> n = 20
>>> a = "a" * n
>>> b = "a" * n
>>> assert id(a) == id(b)  # raises AssertionError

In another two cases (6 and 7), you're not causing any changes to the length or the arrangement of the string:

*

*string[:len(string)] optimises to string

*adding an empty string will never change an existing string

The interpreter is able to optimise these to no-ops.
In examples 5 and 8, it's impossible for the interpreter to know whether the string will be changed without actually performing the operation (i.e. we know that a[::-1] == a, but checking that would require as much work as creating a new string anyway!), so it'll return a new string.


text:
Q: Website broken after installing DSO My website is broken after installing DSO, by DSO I mean the PHP handler that's supposed to speed up a website, here: http://boomshadow.net/tech/php-handlers/
First the website was working as expected.
Then, after requesting my hosting company to install DSO (in order to get APC running), my website isn't working.
Edit
The problem is that it now shows a page full of warnings saying that included files were not found. Like this:
Warning: include(): Filename cannot be empty in /home/mydomain/public_html/index.php on line 14

Warning: include(): Failed opening '' for inclusion (include_path='.:/usr/lib/php:/usr/local/lib/php') in /home/mydomain/public_html/index.php on line 14

Line 14 looks like this :
include ("include/header.php");
I'm getting similar errors for all lines using the include command, and all of them were working perfectly fine before the DSO installation.
Why is this happening? How can I fix it and make my PHP code work aggain? There's nothing wrong with the code, it was working perfectly fine before the DSO installation. I've checked everywhere but I can't seem to figure out if installing DSO also requires some configuration changes.

A: *

*Check the permissions of the files. DSO operates as the Web Server and not as the User.

*Hire a server administrator.


text:
Q: Data structure for stacked intervals I have a list of items with integral widths, which can be interpreted as intervals stacked together from left to right. For example, say the items are A,B,C,D,E and F and have widths 5,2,2,3,2 and 4 respectively:

The numbers below items indicate offsets from the start of the list.
I am looking for a data structure which efficiently supports those operations, ideally in less than O(n):

*

*Find an item from at a given position. For example, the item at position 11 is D since it spans from 9 to 12, and the item at position 14 is F since it starts there.

*Insert an item between any two existing items, or remove any existing item. This should shift the position of subsequent items. For example, removing item E should cause item F to shift left two positions so it would then span from 12 to 16.

I was thinking of using something similar to a skip list, with each level storing the width it encompasses in the level below, but I'm not too sure about what performance characteristics I could get.
Any suggestions?

A: How about a variant of the rope.
But instead of having strings at the leaves, it has intervals.
Finding the interval containing a particular position would be O(log n) (just modify the indexing algorithm of the rope to return the leaf instead of indexing into it).
Inserting an item anywhere would be O(log n) (by splitting once and concatenating twice, all of which take O(log n)).
Unlike in a skiplist, which is probabilistic in nature and has O(n) worst cases if you run into some bad luck, those operations would be O(log n) guaranteed (assuming you use the O(log n) balancing-concatenate).


text:
Q: QueryOver – ensure adding a join table only once I have a fairly complex use case that requires performing the same SQL tasks conditionally in various parts of the code. I wanted to duplicate as little code as possible, so I built a few static helper methods that allow me to add some JOIN statements when needed.
I know this probably could've been done a bit more cleanly with extensions, but for now my code looks something like this:
static class Foo
{
    // Actually adds some filters which need additional JOINs
    public static IQueryOver<Transaction, Transaction> FromRetailer(Retailer retailer, IQueryOver<Transaction, Transaction> baseQuery = null)
    {
        RetailLocation retailLocation = null;

        return ForRetailerBase(baseQuery)
            .Where(t => retailLocation.Retailer == retailer);
    }

    // Auxiliary method which only adds some JOINs needed in various places
    public static IQueryOver<Transaction, Transaction> ForRetailerBase(IQueryOver<Transaction, Transaction> baseQuery = null)
    {
        if (baseQuery == null)
            baseQuery = QueryOver(); // Custom method that creates a vanilla IQueryOver instance

        // Add all sorts of JOINs needed to query the retailer
        return baseQuery
            .JoinAlias(...)
            .Left.JoinAlias(...)
            // and so on
        ;
    }
}

In the business logic, I either need to actually filter by retailer (in which case I call FromRetailer(), which calls ForRetailerBase() for me), or I don't need to filter by retailer – but I still need the JOINs added by ForRetailerBase() later on for grouping. Calling ForRetailerBase() unconditionally obviously breaks things when FromRetailer() is also called.
I'm currently solving this in a very clumsy fashion, by using a boolean in the business logic in order to execute ForRetailerBase() conditionally, only if FromRetailer() isn't executed.
I realize this could be fixed on two levels: either use a more adequate pattern altogether, or add those JOINs conditionally in ForRetailerBase(), by interrogating the baseQuery object to determine whether it already has the necessary JOINs. I'd rather go with the first approach, if one is available (this part of the code is still relatively young, and I can easily refactor it) – but I'll settle for the second approach as well. Problem is, I don't know how to advance in either direction.
I also realize the superficial solution is to remove the call to ForRetailerBase() from method FromRetailer(), and calling it unconditionally from the business logic, but that's just as bad as my current solution, because it requires my business logic to know how those methods work internally.

A: ForRetailerBase, FromRetailer looks to me as something the business logic should not know at all. It looks like query helpers, which should be handled by a query repository.
Such repository will expose querying methods for the business, methods which would internally call your ForRetailerBase or FromRetailer as required.
This way, your business will not need knowledge of how to build your queries, and your querying logic will still be factorized, inside the repository.
Side note: your question does not really look bound to the specific technologies you are using. It looks to me more as a code design question. Maybe should you ask it on https://softwareengineering.stackexchange.com/ instead, which is meant for such questions (see its on topic page).