Q: Can anyone help me with this shadow upload script? I have the shadow uploader also and works great for the 5 form fields (added 2 from original code) in the exmple but want 11, as soon as i add an extra field I get an error:
Request object error 'ASP 0104 : 80004005'
Operation not Allowed
/a20couk/includes/ShadowUploader.asp, line 56

Here is my extra code the shadowuploader include remains the same:

<%
Dim objUpload
If Request("action")="1" Then
    Set objUpload=New ShadowUpload
    If objUpload.GetError<>"" Then
        Response.Write("sorry, could not upload: "&objUpload.GetError)
    Else
        Response.Write("found "&objUpload.FileCount&" files...
")
        For x=0 To objUpload.FileCount-1
            Response.Write("file name: "&objUpload.File(x).FileName&"
")
            Response.Write("file type: "&objUpload.File(x).ContentType&"
")
            Response.Write("file size: "&objUpload.File(x).Size&"
")
            Response.Write("image width: "&objUpload.File(x).ImageWidth&"
")
            Response.Write("image height: "&objUpload.File(x).ImageHeight&"
")
            If (objUpload.File(x).ImageWidth>200) Or (objUpload.File(x).ImageHeight>200) Then
                Response.Write("image to big, not saving!")
            Else
                Call objUpload.File(x).SaveToDisk(Server.MapPath("../../tempuloads/"), "")
                Response.Write("file saved successfully!")
            End If
            Response.Write("
")
        Next
        Response.Write("thank you, "&objUpload("name"))
    End If
End If
%>
<form action="<%=Request.ServerVariables( "Script_Name" )%>?action=1"         enctype="multipart/form-data" method="POST">
File1: <input type="file" name="file1" />

File2: <input type="file" name="file2" />

File3: <input type="file" name="file3" />

File4: <input type="file" name="file4" />

File5: <input type="file" name="file5" />

File6: <input type="file" name="file6" />

File7: <input type="file" name="file7" />

File8: <input type="file" name="file8" />

File9: <input type="file" name="file9" />

File10: <input type="file" name="file10" />

File11: <input type="file" name="file11" />

Name: <input type="text" name="name" />

<button type="submit">Upload</button>
</form>

Been tearing hair out as changed alot of settings one by one nothing worked, will lose all my hair if not resolved quickly!!
The shadow include file:
    <%
'constants:
Const MAX_UPLOAD_SIZE=1500000 'bytes
Const MSG_NO_DATA="nothing to upload!"
Const MSG_EXCEEDED_MAX_SIZE="you exceeded the maximum upload size!"
Const SU_DEBUG_MODE=False

Class ShadowUpload
    Private m_Request
    Private m_Files
    Private m_Error

    Public Property Get GetError
        GetError = m_Error
    End Property

    Public Property Get FileCount
        FileCount = m_Files.Count
    End Property

    Public Function File(index)
        Dim keys
        keys = m_Files.Keys
        Set File = m_Files(keys(index))
    End Function

    Public Default Property Get Item(strName)
        If m_Request.Exists(strName) Then
            Item = m_Request(strName)
        Else
            Item = ""
        End If
    End Property

    Private Sub Class_Initialize
        Dim iBytesCount, strBinData

        'first of all, get amount of uploaded bytes:
        iBytesCount = Request.TotalBytes

        WriteDebug("initializing upload, bytes: " & iBytesCount & "
")

        'abort if nothing there:
        If iBytesCount=0 Then
            m_Error = MSG_NO_DATA
            Exit Sub
        End If

        'abort if exceeded maximum upload size:
        If iBytesCount>MAX_UPLOAD_SIZE Then
            m_Error = MSG_EXCEEDED_MAX_SIZE
            Exit Sub
        End If

        'read the binary data:
        strBinData = Request.BinaryRead(iBytesCount)

        'create private collections:
        Set m_Request = Server.CreateObject("Scripting.Dictionary")
        Set m_Files = Server.CreateObject("Scripting.Dictionary")

        'populate the collection:
        Call BuildUpload(strBinData)
    End Sub

    Private Sub Class_Terminate
        Dim fileName
        If IsObject(m_Request) Then
            m_Request.RemoveAll
            Set m_Request = Nothing
        End If
        If IsObject(m_Files) Then
            For Each fileName In m_Files.Keys
                Set m_Files(fileName)=Nothing
            Next
            m_Files.RemoveAll
            Set m_Files = Nothing
        End If
    End Sub

    Private Sub BuildUpload(ByVal strBinData)
        Dim strBinQuote, strBinCRLF, iValuePos
        Dim iPosBegin, iPosEnd, strBoundaryData
        Dim strBoundaryEnd, iCurPosition, iBoundaryEndPos
        Dim strElementName, strFileName, objFileData
        Dim strFileType, strFileData, strElementValue

        strBinQuote = AsciiToBinary(chr(34))
        strBinCRLF = AsciiToBinary(chr(13))

        'find the boundaries
        iPosBegin = 1
        iPosEnd = InstrB(iPosBegin, strBinData, strBinCRLF)
        strBoundaryData = MidB(strBinData, iPosBegin, iPosEnd-iPosBegin)
        iCurPosition = InstrB(1, strBinData, strBoundaryData)
        strBoundaryEnd = strBoundaryData & AsciiToBinary("--")
        iBoundaryEndPos = InstrB(strBinData, strBoundaryEnd)

        'read binary data into private collection:
        Do until (iCurPosition>=iBoundaryEndPos) Or (iCurPosition=0)
            'skip non relevant data...
            iPosBegin = InstrB(iCurPosition, strBinData, AsciiToBinary("Content-Disposition"))
            iPosBegin = InstrB(iPosBegin, strBinData, AsciiToBinary("name="))
            iValuePos = iPosBegin

            'read the name of the form element, e.g. "file1", "text1"
            iPosBegin = iPosBegin+6
            iPosEnd = InstrB(iPosBegin, strBinData, strBinQuote)
            strElementName = BinaryToAscii(MidB(strBinData, iPosBegin, iPosEnd-iPosBegin))

            'maybe file?
            iPosBegin = InstrB(iCurPosition, strBinData, AsciiToBinary("filename="))
            iPosEnd = InstrB(iPosEnd, strBinData, strBoundaryData)
            If (iPosBegin>0) And (iPosBegin<iPosEnd) Then
                'skip non relevant data..
                iPosBegin = iPosBegin+10

                'read file name:
                iPosEnd = InstrB(iPosBegin, strBinData, strBinQuote)
                strFileName = BinaryToAscii(MidB(strBinData, iPosBegin, iPosEnd-iPosBegin))

                'verify that we got name:
                If Len(strFileName)>0 Then
                    'create file data:
                    Set objFileData = New FileData
                    objFileData.FileName = strFileName

                    'read file type:
                    iPosBegin = InstrB(iPosEnd, strBinData, AsciiToBinary("Content-Type:"))
                    iPosBegin = iPosBegin+14
                    iPosEnd = InstrB(iPosBegin, strBinData, strBinCRLF)
                    strFileType = BinaryToAscii(MidB(strBinData, iPosBegin, iPosEnd-iPosBegin))
                    objFileData.ContentType = strFileType

                    'read file contents:
                    iPosBegin = iPosEnd+4
                    iPosEnd = InstrB(iPosBegin, strBinData, strBoundaryData)-2
                    strFileData = MidB(strBinData, iPosBegin, iPosEnd-iPosBegin)

                    'check that not empty:
                    If LenB(strFileData)>0 Then
                        objFileData.Contents = strFileData

                        'append to files collection if not empty:
                        Set m_Files(strFileName) = objFileData
                    Else
                        Set objFileData = Nothing
                    End If
                End If
                strElementValue = strFileName
            Else
                'ordinary form value, just read:
                iPosBegin = InstrB(iValuePos, strBinData, strBinCRLF)
                iPosBegin = iPosBegin+4
                iPosEnd = InstrB(iPosBegin, strBinData, strBoundaryData)-2
                strElementValue = BinaryToAscii(MidB(strBinData, iPosBegin, iPosEnd-iPosBegin))
            End If

            'append to request collection
            m_Request(strElementName) = strElementValue

            'skip to next element:
            iCurPosition = InstrB(iCurPosition+LenB(strBoundaryData), strBinData, strBoundaryData)
        Loop
    End Sub

    Private Function WriteDebug(msg)
        If SU_DEBUG_MODE Then
            Response.Write(msg)
            Response.Flush
        End If
    End Function

    Private Function AsciiToBinary(strAscii)
        Dim i, char, result
        result = ""
        For i=1 to Len(strAscii)
            char = Mid(strAscii, i, 1)
            result = result & chrB(AscB(char))
        Next
        AsciiToBinary = result
    End Function

    Private Function BinaryToAscii(strBinary)
        Dim i, result
        result = ""
        For i=1 to LenB(strBinary)
            result = result & chr(AscB(MidB(strBinary, i, 1)))
        Next
        BinaryToAscii = result
    End Function
End Class

Class FileData
    Private m_fileName
    Private m_contentType
    Private m_BinaryContents
    Private m_AsciiContents
    Private m_imageWidth
    Private m_imageHeight
    Private m_checkImage

    Public Property Get FileName
        FileName = m_fileName
    End Property

    Public Property Get ContentType
        ContentType = m_contentType
    End Property

    Public Property Get ImageWidth
        If m_checkImage=False Then Call CheckImageDimensions
        ImageWidth = m_imageWidth
    End Property

    Public Property Get ImageHeight
        If m_checkImage=False Then Call CheckImageDimensions
        ImageHeight = m_imageHeight
    End Property

    Public Property Let FileName(strName)
        Dim arrTemp
        arrTemp = Split(strName, "\")
        m_fileName = arrTemp(UBound(arrTemp))
    End Property

    Public Property Let CheckImage(blnCheck)
        m_checkImage = blnCheck
    End Property

    Public Property Let ContentType(strType)
        m_contentType = strType
    End Property

    Public Property Let Contents(strData)
        m_BinaryContents = strData
        m_AsciiContents = RSBinaryToString(m_BinaryContents)
    End Property

    Public Property Get Size
        Size = LenB(m_BinaryContents)
    End Property

    Private Sub CheckImageDimensions
        Dim width, height, colors
        Dim strType

        '''If gfxSpex(BinaryToAscii(m_BinaryContents), width, height, colors, strType) = true then
        If gfxSpex(m_AsciiContents, width, height, colors, strType) = true then
            m_imageWidth = width
            m_imageHeight = height
        End If
        m_checkImage = True
    End Sub

    Private Sub Class_Initialize
        m_imageWidth = -1
        m_imageHeight = -1
        m_checkImage = False
    End Sub

    Public Sub SaveToDisk(strFolderPath, ByRef strNewFileName)
        Dim strPath, objFSO, objFile
        Dim i, time1, time2
        Dim objStream, strExtension

        strPath = strFolderPath&"\"
        If Len(strNewFileName)=0 Then
            strPath = strPath & m_fileName
        Else
            strExtension = GetExtension(strNewFileName)
            If Len(strExtension)=0 Then
                strNewFileName = strNewFileName & "." & GetExtension(m_fileName)
            End If
            strPath = strPath & strNewFileName
        End If

        WriteDebug("save file started...
")

        time1 = CDbl(Timer)

        Set objFSO = Server.CreateObject("Scripting.FileSystemObject")
        Set objFile = objFSO.CreateTextFile(strPath)

        objFile.Write(m_AsciiContents)

        '''For i=1 to LenB(m_BinaryContents)
        ''' objFile.Write chr(AscB(MidB(m_BinaryContents, i, 1)))
        '''Next

        time2 = CDbl(Timer)
        WriteDebug("saving file took " & (time2-time1) & " seconds.
")

        objFile.Close
        Set objFile=Nothing
        Set objFSO=Nothing
    End Sub

    Private Function GetExtension(strPath)
        Dim arrTemp
        arrTemp = Split(strPath, ".")
        GetExtension = ""
        If UBound(arrTemp)>0 Then
            GetExtension = arrTemp(UBound(arrTemp))
        End If
    End Function

    Private Function RSBinaryToString(xBinary)
        'Antonin Foller, http://www.motobit.com
        'RSBinaryToString converts binary data (VT_UI1 | VT_ARRAY Or MultiByte string)
        'to a string (BSTR) using ADO recordset

        Dim Binary
        'MultiByte data must be converted To VT_UI1 | VT_ARRAY first.
        If vartype(xBinary)=8 Then Binary = MultiByteToBinary(xBinary) Else Binary = xBinary

        Dim RS, LBinary
        Const adLongVarChar = 201
        Set RS = CreateObject("ADODB.Recordset")
        LBinary = LenB(Binary)

        If LBinary>0 Then
            RS.Fields.Append "mBinary", adLongVarChar, LBinary
            RS.Open
            RS.AddNew
            RS("mBinary").AppendChunk Binary
            RS.Update
            RSBinaryToString = RS("mBinary")
        Else
            RSBinaryToString = ""
        End If
    End Function

    Function MultiByteToBinary(MultiByte)
        '© 2000 Antonin Foller, http://www.motobit.com
        ' MultiByteToBinary converts multibyte string To real binary data (VT_UI1 | VT_ARRAY)
        ' Using recordset
        Dim RS, LMultiByte, Binary
        Const adLongVarBinary = 205
        Set RS = CreateObject("ADODB.Recordset")
        LMultiByte = LenB(MultiByte)
        If LMultiByte>0 Then
            RS.Fields.Append "mBinary", adLongVarBinary, LMultiByte
            RS.Open
            RS.AddNew
            RS("mBinary").AppendChunk MultiByte & ChrB(0)
            RS.Update
            Binary = RS("mBinary").GetChunk(LMultiByte)
        End If
        MultiByteToBinary = Binary
    End Function

    Private Function WriteDebug(msg)
        If SU_DEBUG_MODE Then
            Response.Write(msg)
            Response.Flush
        End If
    End Function

    Private Function BinaryToAscii(strBinary)
        Dim i, result
        result = ""
        For i=1 to LenB(strBinary)
            result = result & chr(AscB(MidB(strBinary, i, 1)))
        Next
        BinaryToAscii = result
    End Function

    ':::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::
    ':::                                                             :::
    ':::  This routine will attempt to identify any filespec passed  :::
    ':::  as a graphic file (regardless of the extension). This will :::
    ':::  work with BMP, GIF, JPG and PNG files.                     :::
    ':::                                                             :::
    ':::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::
    ':::          Based on ideas presented by David Crowell          :::
    ':::                   (credit where due)                        :::
    ':::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::
    ':::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::
    ':::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::
    '::: blah blah blah blah blah blah blah blah blah blah blah blah :::
    '::: blah blah blah blah blah blah blah blah blah blah blah blah :::
    '::: blah blah     Copyright *c* MM,  Mike Shaffer     blah blah :::
    '::: bh blah      ALL RIGHTS RESERVED WORLDWIDE      blah blah :::
    '::: blah blah  Permission is granted to use this code blah blah :::
    '::: blah blah   in your projects, as long as this     blah blah :::
    '::: blah blah      copyright notice is included       blah blah :::
    '::: blah blah blah blah blah blah blah blah blah blah blah blah :::
    '::: blah blah blah blah blah blah blah blah blah blah blah blah :::
    ':::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::

    ':::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::
    ':::                                                             :::
    ':::  This function gets a specified number of bytes from any    :::
    ':::  file, starting at the offset (base 1)                      :::
    ':::                                                             :::
    ':::  Passed:                                                    :::
    ':::       flnm        => Filespec of file to read               :::
    ':::       offset      => Offset at which to start reading       :::
    ':::       bytes       => How many bytes to read                 :::
    ':::                                                             :::
    ':::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::
    Private Function GetBytes(flnm, offset, bytes)
        Dim startPos
        If offset=0 Then
            startPos = 1
        Else
            startPos = offset
        End If
        if bytes = -1 then      ' Get All!
            GetBytes = flnm
        else
            GetBytes = Mid(flnm, startPos, bytes)
        end if
'       Dim objFSO
'       Dim objFTemp
'       Dim objTextStream
'       Dim lngSize
'
'       Set objFSO = CreateObject("Scripting.FileSystemObject")
'
'       ' First, we get the filesize
'       Set objFTemp = objFSO.GetFile(flnm)
'       lngSize = objFTemp.Size
'       set objFTemp = nothing
'
'       fsoForReading = 1
'       Set objTextStream = objFSO.OpenTextFile(flnm, fsoForReading)
'
'       if offset > 0 then
'           strBuff = objTextStream.Read(offset - 1)
'       end if
'
'       if bytes = -1 then      ' Get All!
'           GetBytes = objTextStream.Read(lngSize)  'ReadAll
'       else
'           GetBytes = objTextStream.Read(bytes)
'       end if
'
'       objTextStream.Close
'       set objTextStream = nothing
'       set objFSO = nothing
    End Function

    ':::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::
    ':::                                                             :::
    ':::  Functions to convert two bytes to a numeric value (long)   :::
    ':::  (both little-endian and big-endian)                        :::
    ':::                                                             :::
    ':::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::
    Private Function lngConvert(strTemp)
        lngConvert = clng(asc(left(strTemp, 1)) + ((asc(right(strTemp, 1)) * 256)))
    end function

    Private Function lngConvert2(strTemp)
        lngConvert2 = clng(asc(right(strTemp, 1)) + ((asc(left(strTemp, 1)) * 256)))
    end function

    ':::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::
    ':::                                                             :::
    ':::  This function does most of the real work. It will attempt  :::
    ':::  to read any file, regardless of the extension, and will    :::
    ':::  identify if it is a graphical image.                       :::
    ':::                                                             :::
    ':::  Passed:                                                    :::
    ':::       flnm        => Filespec of file to read               :::
    ':::       width       => width of image                         :::
    ':::       height      => height of image                        :::
    ':::       depth       => color depth (in number of colors)      :::
    ':::       strImageType=> type of image (e.g. GIF, BMP, etc.)    :::
    ':::                                                             :::
    ':::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::
    function gfxSpex(flnm, width, height, depth, strImageType)
        dim strPNG
        dim strGIF
        dim strBMP
        dim strType
        dim strBuff
        dim lngSize
        dim flgFound
        dim strTarget
        dim lngPos
        dim ExitLoop
        dim lngMarkerSize

        strType = ""
        strImageType = "(unknown)"

        gfxSpex = False

        strPNG = chr(137) & chr(80) & chr(78)
        strGIF = "GIF"
        strBMP = chr(66) & chr(77)

        strType = GetBytes(flnm, 0, 3)

        if strType = strGIF then                ' is GIF
            strImageType = "GIF"
            Width = lngConvert(GetBytes(flnm, 7, 2))
            Height = lngConvert(GetBytes(flnm, 9, 2))
            Depth = 2 ^ ((asc(GetBytes(flnm, 11, 1)) and 7) + 1)
            gfxSpex = True
        elseif left(strType, 2) = strBMP then       ' is BMP
            strImageType = "BMP"
            Width = lngConvert(GetBytes(flnm, 19, 2))
            Height = lngConvert(GetBytes(flnm, 23, 2))
            Depth = 2 ^ (asc(GetBytes(flnm, 29, 1)))
            gfxSpex = True
        elseif strType = strPNG then            ' Is PNG
            strImageType = "PNG"
            Width = lngConvert2(GetBytes(flnm, 19, 2))
            Height = lngConvert2(GetBytes(flnm, 23, 2))
            Depth = getBytes(flnm, 25, 2)
            select case asc(right(Depth,1))
                case 0
                    Depth = 2 ^ (asc(left(Depth, 1)))
                    gfxSpex = True
                case 2
                    Depth = 2 ^ (asc(left(Depth, 1)) * 3)
                    gfxSpex = True
                case 3
                    Depth = 2 ^ (asc(left(Depth, 1)))  '8
                    gfxSpex = True
                case 4
                    Depth = 2 ^ (asc(left(Depth, 1)) * 2)
                    gfxSpex = True
                case 6
                    Depth = 2 ^ (asc(left(Depth, 1)) * 4)
                    gfxSpex = True
                case else
                    Depth = -1
            end select
        else
            strBuff = GetBytes(flnm, 0, -1)     ' Get all bytes from file
            lngSize = len(strBuff)
            flgFound = 0

            strTarget = chr(255) & chr(216) & chr(255)
            flgFound = instr(strBuff, strTarget)

            if flgFound = 0 then
                exit function
            end if

            strImageType = "JPG"
            lngPos = flgFound + 2
            ExitLoop = false

            do while ExitLoop = False and lngPos < lngSize
                do while asc(mid(strBuff, lngPos, 1)) = 255 and lngPos < lngSize
                    lngPos = lngPos + 1
                loop

                if asc(mid(strBuff, lngPos, 1)) < 192 or asc(mid(strBuff, lngPos, 1)) > 195 then
                    lngMarkerSize = lngConvert2(mid(strBuff, lngPos + 1, 2))
                    lngPos = lngPos + lngMarkerSize  + 1
                else
                    ExitLoop = True
                end if
            loop

            if ExitLoop = False then
                Width = -1
                Height = -1
                Depth = -1
            else
                Height = lngConvert2(mid(strBuff, lngPos + 4, 2))
                Width = lngConvert2(mid(strBuff, lngPos + 6, 2))
                Depth = 2 ^ (asc(mid(strBuff, lngPos + 8, 1)) * 8)
                gfxSpex = True
            end if
        end if
    End Function
End Class
%>

thanks

A: it is not allowed to use request.binaryread after you have used the request.form collection.
but your
If Request("action")="1" Then

uses the request.form collection because you are not using request.querystring("action").
after that you instantiate the uploader and this uses in line 56 request.BinaryRead

A: As explained in this answer, the default limit for POST request size is 200KB - typical to Microsoft, the error message in case the limit is exceeded is far from helpful.
To fix this error and allow bigger files and/or more files, you need to change the setting in IIS.
For IIS 7.5 (default for Windows 7) first choose the site then double click "ASP" under IIS:

Now write a number bigger than 200000 as value of "Maximum Requesting Entity Body Limit" under "Limit Properties" section: (15728640 is 15 MB which is reasonable limit)

Click "Apply" in the right sidebar and you're done. Happy programming!


Q: jQuery beginner - accordion menu, but jittery buttons I built an accordion FAQ menu as part of a personal exercise here
There's a slight jitter/shake when clicking the buttons that I can't seem to solve for. I've searched Google, but to no avail for something that works. Any ideas?
Also, is there a more efficient way to write the code? Here's what I have:
(function () {

    $('dd').hide();
    $('dt').click(function(){
        $(this)
            .next()
            .slideDown(100)
            .siblings('dd')
            .slideUp(100);
    });

    $('dd').click(function(){
        $(this).hide();
    });

})();

A: I am not quite sure, but could it be that you're seeing the sub-pixel renderer adjusting the inter-colour border in response to elements on the page moving around?
Unfortunately, if this is the case, there's little you can do about it from a web application.  At best, you can pick a colour scheme with less button border contrast, which would make the wobble less obvious.

A: Have you tried to change the jquery custom theme that you are currently using?

A: Doing animations with jQuery is actually quite expensive in terms of performance. I would suggest not using animations that is likely your problem.
Also, you could also use jquery ui as they have solved the accordion problem already. No sense in re-inventing the wheel

A: Try toggling some transition effects to get your desired result. Use CSS3 where possible; or stick with jQuery if you'd rather.
$(this).animate({
    'paddingBottom': 5,
}, 300, 'linear')


Q: Vue 3 rellax.js usage i have installed rellax.js in vue3 project.

import App from './App.vue'

import VueRellax from 'vue-rellax'

createApp(App).use(VueRellax).mount(#app)

but when i add rellax class on any components template tags its not working

<section class="rellax section portfolio-section pd-34" id="portfolio">
     <PortfolioComponent />
</section>

not working when i add class rellax in component class even doesnot show in inspect

A: It looks like vue-rellax was never rewritten for Vue 3. You're likely better off to use the rellax library and import it into your components or as a window variable.
App.vue:
<script setup>
    import { onMounted } from 'vue';

    import Rellax from 'rellax'

    onMounted(() => {
      let rellax = new Rellax('.rellax');
    })
</script>


Q: Reading Core Data as Objects I have 1 entity in my database "Message" with the values MessageID, messageText and i want to read every row of Core Data, make an object of my class "Message" and put the new object into an array.
It's the first time I'm using Core Data and I don't quite get it yet, how I manage to do that.

A: Create a fetch request for the entity you wish to retrieve. Don't give it a predicate, set whatever sort descriptor you want.
Execute the fetch request in a managed object context and it will return an array of all the objects of that entity.
This is purposely just a descriptive answer, you can find the specifics of how to do this from the Core Data introductory documentation; you are new in Core Data and this is a good way to learn it.
Also - don't think of Core Data in terms of rows of data that you turn into objects. It's an Object-Relationship graph. It stores the objects of entities and their relationships between them. You don't turn the "rows" into objects, you get the objects back directly.

A: The response of @Abizern with code :
NSManagedObjectContext *moc = // your managed object context;
NSEntityDescription *entityDescription = [NSEntityDescription
    entityForName:@"Message" inManagedObjectContext:moc];
NSFetchRequest *request = [[NSFetchRequest alloc] init];
[request setEntity:entityDescription];

// You can also add a predicate or sort descriptor to your request

NSError *error;
NSArray *array = [moc executeFetchRequest:request error:&error];
if (array == nil)
{
    // Deal with error...
}


Q: Update statement in stored procedure with varbinary parameter I have the following table:
CREATE TABLE NZQA_Unit(
    NZQAUnitID                          int IDENTITY(1,1) PRIMARY KEY NOT NULL,
    NZQAUnitNumber                      int NOT NULL,
    Title                               nvarchar(255) NOT NULL,
    Level                               smallint NOT NULL,
    Credits                             smallint NOT NULL,
    Classification                      nvarchar(255) NULL,
    AvailableGrade                      int NULL DEFAULT 1,
    Purpose                             nvarchar(max) NULL,
    Validity                            int NOT NULL DEFAULT 1, -- by default the unit will be 'Current'
    Document                            VARBINARY(MAX) NULL, -- for being able to upload a PDF or Word document
    DocumentExtension                   varchar(5) NULL, -- for storing the file extension
    CONSTRAINT AK_NZQA_Unit_Title           UNIQUE(Title),
    CONSTRAINT AK_NZQA_Unit_Number          UNIQUE(NZQAUnitNumber),
    CONSTRAINT FK_NZQA_Unit_Validity        FOREIGN KEY (Validity) REFERENCES NZQA_Unit_Validity (ValidityID),
    CONSTRAINT FK_NZQA_Unit_AvailableGrade  FOREIGN KEY (AvailableGrade) REFERENCES NZQA_Unit_Assessment_Grade (AssessmentGradeID),
    CONSTRAINT CK_NZQA_Unit_Title           CHECK ((len(ltrim(rtrim(Title)))>(2))),
    CONSTRAINT CK_NZQA_Unit_ID_Range        CHECK (NZQAUnitNumber >= 1000 AND NZQAUnitNumber <= 99999), --Inclusive
    CONSTRAINT CK_NZQA_Unit_Level           CHECK (Level >= 1 AND Level <= 10), -- Level must be between 1 and 10 https://www.nzqa.govt.nz/studying-in-new-zealand/understand-nz-quals/
    CONSTRAINT CK_NZQA_Unit_Credits         CHECK (Credits >= 1 AND Credits <= 999), -- 999 has been set arbitrarily but it's high enough to fit an Engineering Degree
    CONSTRAINT CK_NZQA_Unit_DocumentSize    CHECK (DATALENGTH(Document) <= 524288), -- Maximum size 500 KB https://stackoverflow.com/questions/34741079/can-i-set-2-mb-for-maximum-size-of-varbinary      https://www.gbmb.org/mb-to-bytes
    CONSTRAINT CK_NZQA_Unit_DocumentExtension   CHECK (DocumentExtension IN ('.pdf', '.doc', '.docx')) -- this check is not case sensitive, i.e. '.DOCX' won't trigger an error
    );
GO

And I'm writing the following stored procedure:
DROP PROCEDURE  IF EXISTS  Modify_NZQA_Unit
GO

CREATE PROCEDURE Modify_NZQA_Unit
    @NZQAUnitID                 int,
    @NZQAUnitNumber             int,
    @Title                      nvarchar(255),
    @Level                      smallint,
    @Credits                    smallint,
    @Classification             nvarchar(255) NULL,
    @AvailableGrade             int,
    @Purpose                    nvarchar(max),
    @Validity                   int,
    @Document                   VARBINARY(MAX),
    @DocumentExtension          varchar(5),
    @overwriteFile              bit -- 1 to overwrite, 0 to no overwrite
AS
BEGIN
    IF (@NZQAUnitID IS NULL)
    BEGIN
        THROW 51006, 'You must input the NZQA identifier (NZQAUnitID)', 1;
    END

    SET @Title = Replace(@Title, '''', '''''') -- singles quotes must be escaped
    SET @Classification = Replace(@Classification, '''', '''''')
    SET @Purpose = Replace(@Purpose, '''', '''''')
    SET @DocumentExtension = Replace(@DocumentExtension, '''', '''''')

    DECLARE @updateStatement AS NVARCHAR(1000);
    SET @updateStatement = 'UPDATE NZQA_Unit SET NZQAUnitNumber = '+CONVERT(VARCHAR, @NZQAUnitNumber)+', Title = '''+@Title+''', Level = '+CONVERT(VARCHAR, @Level)+', Credits = '+CONVERT(VARCHAR, @Credits)+', Classification = '''+@Classification+''',  AvailableGrade = '+CONVERT(VARCHAR, @AvailableGrade)+', Purpose = '''+@Purpose+''', Validity = '+CONVERT(VARCHAR, @Validity)

    IF (@overwriteFile IS NULL)
    BEGIN
        THROW 51007, 'Variable @overwriteFile cannot be null', 1;
    END
    ELSE
    BEGIN
        IF (@overwriteFile = 1)
        BEGIN
            IF (@Document IS NULL)
            BEGIN
                THROW 51008, 'If the variable @overwriteFile is set to 1, a file (@Document) must be provided', 1;
            END
            IF (@DocumentExtension IS NULL)
            BEGIN
                THROW 51009, 'If the variable @overwriteFile is set to 1, the document extension (@DocumentExtension) must be provided', 1;
            END

            SET @updateStatement = @updateStatement + ', Document = '+'HERE WILL COME THE VARBINARY'+', DocumentExtension = '''+@DocumentExtension + ''' '

            --DOESN'T WORK: EXEC('UPDATE NZQA_Unit SET NZQAUnitNumber = '+@NZQAUnitNumber+', Title = '''+@Title+''', Level = '+@Level+', Credits = '+@Credits+', Classification = '''+@Classification+''',  AvailableGrade = '+@AvailableGrade+', Purpose = '''+@Purpose+''', Validity = '+@Validity + ', Document = ' + @document + ', DocumentExtension = '''+@DocumentExtension + ''' ' +' WHERE NZQAUnitID = '+@NZQAUnitID)
            UPDATE NZQA_Unit SET NZQAUnitNumber = @NZQAUnitNumber, Title = @Title, Level = @Level, Credits = @Credits, Classification = @Classification,  AvailableGrade = @AvailableGrade, Purpose = @Purpose, Validity = @Validity, Document = @document, DocumentExtension = @DocumentExtension WHERE NZQAUnitID = @NZQAUnitID
        END
        ELSE
        BEGIN
            UPDATE NZQA_Unit SET NZQAUnitNumber = @NZQAUnitNumber, Title = @Title, Level = @Level, Credits = @Credits, Classification = @Classification,  AvailableGrade = @AvailableGrade, Purpose = @Purpose, Validity = @Validity WHERE NZQAUnitID = @NZQAUnitID
        END
    END

    SET @updateStatement = @updateStatement +' WHERE NZQAUnitID = '+CONVERT(VARCHAR, @NZQAUnitID)
    PRINT @updateStatement
END
GO

How could I insert the varbinary data (@Document) into the @updateStatement variable? That way I could simply do a EXEC(@updateStatement)?
Code to execute the procedure below:
DECLARE @current    AS INT = 1
DECLARE @expiring   AS INT = 2
DECLARE @expired    AS INT = 3
DECLARE @achieved   AS INT = 1
DECLARE @datos      AS VARBINARY(30) = CONVERT(varbinary(30), N'this IS a test')
INSERT NZQA_Unit (NZQAUnitNumber, [Title], [Level], [Credits], [Classification], [AvailableGrade], [Purpose], Validity) VALUES (6401, N'Provide first aid', 2, 1, N'Health Studies > First Aid', @achieved, N'People credited with this unit standard are able to provide first aid.', @current)

EXEC Modify_NZQA_Unit 1, 6424, N'Provide first aid', 2, 1, N'Health Studies > First Aid', @achieved, N'People credited with this unit standard are able to provide first aid.', @current, @datos, '.pdf', 1


Q: Heroku Automated Generated Name How to change heroku automated created name (ex: glacial-dawn-22102 ) its not related to my project name!
When I input the command git push heroku main then it creates the name of the file. Is there any opton to modify this?
git push heroku main


Q: Recording video with webcam using VideoCapture I want to record a video with python (using my webcam) and I came across VideoCapture which was easy to install on windows. I know there is OpenCV out there, but that was too much for me.
So far I can create every 0.04 seconds a .jpg with this code:
from VideoCapture import Device
import time
cam = Device(devnum=0) #uses the first webcame which is found

x = 0
while True:
  cam.saveSnapshot(str(x)+'.jpg', timestamp=3, boldfont=1) #########################
  x += 1
  time.sleep(0.04)

0.04 seconds * 25 = 1. So what I am planning to do is an animated gif, that has 25 frames/sec. If somebody of you knows how to produce a real video file like .mp4, I really would prefer the .mp4 rather than .gif. However if thats not possible, the next thing I need to do is, to concatenate all .jpg files (0.jpg, 1.jpg, 2.jpg ...) but as you can imagine with increasing recording time I get A LOT of files. So I was wondering if it would be possible to write the .jpg files (the frames) to one .gif file consecutively. If thats not possible in python, how would you concatenate the jpg files to get an animated gif in the end?

A: OpenCV will make it more easy.  You will find more problem in your method.  To use opencv you have to install 1 more package known as numpy (numerical python).  It's easy to install.  If you want to install it automatically:
Install

*

*Install pip manually

*After that go to your cmd>python folder>Lib>site-packages and type pip install numpy *but for using pip you have to be in internet access.

*After installation of numpy just type pip intall opencv.

Now you can import all the packages. If numpy somehow fails, maunually downlaod numpy 1.8.0 and install it.


Q: What is lastApplied and matchIndex in raft protocol for volatile state in server? I am using the following pdf as reference.
It says that lastApplied is the highest log entry applied to state machine, but how is that any different than the commitIndex?
Also is the matchIndex on leader just the commitIndex on followers? If not what is the difference?

A: Your observation is reasonable: most of the time, nextIndex equals matchIndex + 1, but it is not always the case.
For example, when a leader is initiated, matchIndex is initiated to the 0, while nextIndex is initiated to the last log index + 1.
The difference here is because these two fields are used for different purposes: matchIndex is an accurate value indicating the index up to which all the log entries in leader and follower match. However, nextIndex is only an optimistic "guess" indicating which index the leader should try for the next AppendEntries operation, it can be a good guess (i.e. it equals matchIndex + 1) in which case the AppendEntries operation will succeed, but it can also be a bad guess (e.g. in the case when a leader was just initiated) in which case the AppendEntries will fail so that the leader will decrement nextIndex and retry.
As for lastApplied, it's simply another accurate value indicating the index up to which all the log entries in a follower have been applied to the underlying state machine. It's similar to matchIndex in that they both are both accurate values instead of heuristic "guess", but they really mean different things and serve for different purposes.

A:
... lastApplied is the highest log entry applied to state machine, but how is that any different than the commitIndex?

These are different in a practical system because the component that commits the data in the log is typically separate from the component that applies it to replicated state machine or database. The commitIndex is typically just nanoseconds or maybe a few milliseconds more up-to-date than lastApplied.

Is the matchIndex on leader just the commitIndex on followers? If not what is the difference?

They are different. There is a period of time when the data is on a server and not yet committed, such as during the replication itself.
The leader keeps track of the latest un-committed data on each of its peers and only need to send log[matchIndex[peer], ...] to each peer instead of the whole log. This is especially useful if the peer is significantly behind the leader; because the leader can update the peer with a series of small AppendEntries calls, incrementally bringing the peer up to date.

A: *

*commit is not mean already applied, there is time different between them. but eventually applied will catch up commit index.

*matchIndex[i] which is saved in leader is equal to follower_i's commitIndex, and they are try to catch up to nextIndex


Q: gradlew.bat invalid directory in android studio How do I address the following error?
ERROR: JAVA_HOME is set to an invalid directory: C:\Program Files\Java\jdk1.7.0_67\bin;

Please set the JAVA_HOME variable in your environment to match the
location of your Java installation.
I've been researching this for hours today but I haven't been able to find a solution that works for me.
My JAVA_HOME is set to C:\Program Files\Java\jdk1.7.0_67;
I tried setting it to JAVA_HOME C:\Progra~2\Java\jdk1.7.67; per the advise of a different thread but gradle is still throwing the same error in android studio.
Does anyone have an idea about what might be going wrong right now?

A: You need to remove the bin from the end of your JAVA_HOME variable. If Android Studio still gives the same error, close and restart it. If you still get the same error, restart your machine.


Q: Programmatically layout buttons I am new to Android Development, having much experience in desktop and Web Application coding, and am just getting to grips with how the view layouts work. I have been using Linear Layouts and weights previously to solve my design issues, but due (I believe) to this design not being, uniformly tabular I am struggling.

I want Tag5 next to Tag0 and under Tag1, and then Tag 6 and 7 next to it.  My code to do this so far is
    Display display = getWindowManager().getDefaultDisplay();
    Point size = new Point();
    display.getSize(size);
    int width = size.x;
    int height = size.y;

    String tag;
    for (int i = 0; i <= 7; i++) {
        int indColumn = width / 7;
        int indColumnHeight = height / 9;
        tag = "#tag" + i;
        View tagView = layoutInflater.inflate(R.layout.layout_child, null, false);
        Button tagTextView = (Button) tagView.findViewById(R.id.tagTextView);
        if (i == 0 || i == 3 || i == 6 || i == 7) {
            tagTextView.setWidth(Math.round(indColumn * 2));
        } else {
            tagTextView.setWidth(Math.round(indColumn));
        }
        if (i == 0) {
            tagTextView.setHeight(Math.round(indColumnHeight * 2));
        } else {
            tagTextView.setHeight(Math.round(indColumnHeight));
        }

        tagTextView.setText(tag);
        tagLayout.addView(tagView);

I have tried adding
        if(i==5) {
            RelativeLayout.LayoutParams lp = new RelativeLayout.LayoutParams(RelativeLayout.LayoutParams.WRAP_CONTENT, RelativeLayout.LayoutParams.WRAP_CONTENT);
            lp.addRule(RelativeLayout.RIGHT_OF, 0);
            lp.addRule(RelativeLayout.BELOW, 1);
            tagTextView.setLayoutParams(lp);
        }

before the tagTextView.set Text but it is making no difference
The xml looks like this for an individual button
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_weight="1">
<Button
    android:id="@+id/tagTextView"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:background="#a000"
    android:textColor="#fff"/>
</RelativeLayout>

A: I took what EasyJoin Dev said, and tweaked it a little, I created a Relative layout using the layout_toEndOf and layout_below options, and then in the activities create method I overrode the width and height programmatically to get my percentage based sizing.


Q: Kieran Healy's emacs starter kit in linux (fedora19): "/bin/bash: osascript: command not found" message I am user of Kieran Healy's Emacs Starter Kit. I have run it on the Fedora distro of Linux for around a year or so.  Things have always run smoothly, but now that I have upgraded from Fedora17 to Fedora19, when I  try to commit in Magit, I get the following message: /bin/bash: osascript: command not found
I understand I get this message because Kieran customizes  the ESSK for the Mac OS. So I thought I just needed to tweak this feature. To do that, I need to find where in the emacs dot files is the call to an osascript, but when I use Grep to find the string 'osascript', I get no match.
Hence my question: does anyone know where in the emacs dot files there is a call to an  osascript for the  commit command in git to run?
Thank you very much!

A: This is based on a current version of the starter kit:  http://kieranhealy.org/resources/emacs-starter-kit.html
MP:~ HOME$ grep -inIEr --color=ALWAYS -C1 "osascript" .../emacs-starter-kit-master
.../emacs-starter-kit-master/kjhealy.org-189-    (defun raise-emacs-on-aqua()
.../emacs-starter-kit-master/kjhealy.org:190:    (shell-command "osascript -e 'tell application \"Emacs\" to activate' &"))
.../emacs-starter-kit-master/kjhealy.org-191-    (add-hook 'server-switch-hook 'raise-emacs-on-aqua)
MP:~ HOME$


Q: Delete action doesn't work for entities without dependencies in entity framework Here is my Delete action code and when I try to delete an entity which doesn't contain any dependencies. It always return index without delete. I just want to set it only for the entities with dependencies and others should allow deleted and add to the log.
    // GET: Company/5/Delete
        [Route("{companyPk:int}/Delete")]
        public async Task<ActionResult> Delete(int? companyPk)
        {
            //Validate parameters
            if (companyPk == null)
            {
                return new HttpStatusCodeResult(HttpStatusCode.BadRequest, "Company identifier is missing.");
            }

            //Get the model from db
            Company company = await _work.Companies.GetAsync(companyPk);
            if (company == null)
            {
                return HttpNotFound();
            }

            //Convert model to dto
            CompanyDto companyDto = _mapper.Map<CompanyDto>(company);

            return View(companyDto);
        }

        // POST: Company/5/Delete
        [HttpPost, ActionName("Delete")]
        [ValidateAntiForgeryToken]
        [Route("{companyPk:int}/Delete")]
        public async Task<ActionResult> DeleteConfirmed(int companyPk)
        {
            //Get the model from db
            Company company = await _work.Companies.GetAsync(companyPk);

            var Related = _work.Companies.Where(i => i.CompanyPk == companyPk)
                .Include(i => i.Departments)
                .Include(i => i.Locations);
                //.FirstOrDefault();

            if (Related != null)
            {
                ViewBag.Message = String.Format("Company Pk has dependencies for Department and Location. Can't Delete");
                return RedirectToAction("Index");
            }

            //Prepare log model
            var logCompany = _mapper.Map<LogCompany>(company);
                logCompany.RecordId = 0;
                Utilities.Instance.SetLogEntityProperties(logCompany, "D");

                //Save model to db
                _work.LogCompanies.Add(logCompany);
                _work.Companies.Remove(company);
                await _work.CompleteAsync();

                return RedirectToAction("Index");
        }

A: Have you tried to add this line after the delete one?
_work.SaveChanges();

As far as i know, without it, you just delete locally, and savechanges edit into the DB as well.


Q: How to initialise QTextEdit find options I am trying to set the options in the following call:
bool QTextEdit::find(const QString &exp, QTextDocument::FindFlags options = QTextDocument::FindFlags())

But the signature of option is complicated for a Python programmer. I tried the following:
option = 0
option = option | QTextDocument.FindBackward
# continue to check other checkboxes and build up the option this way

Unfortunately, the error is that 'int' is unexpected. I understand that since the option=0, then the following OR operation probably didn't yield an int type as well. But how to get a the proper starting null/unset/zero value?

A: If you would have default value let this parameter unfilled:
doc = QTextDocument()
doc.find("aaa")

If you would like to use flag, do not read value from documentation, but use
QTextDocument.FindBackward
QTextDocument.FindCaseSensitively
QTextDocument.FindWholeWords

If you would like to have or use | operator:
QTextDocument.FindWholeWords |  QTextDocument.FindBackward

If you have default value in function signature, you not need to provide this argument.

A: The error is caused by a minor bug that occasionally appears in PyQt. If you update to the latest version, the error will probably go away. However, if you can't update, or if you want to bullet-proof your code against this problem, a work-around is to initialise the variable like this:
>>> option = QTextDocument.FindFlag(0)
>>> option = option | QTextDocument.FindBackward

This will now guarantee that option has the expected type. The correct flag to use can be found by explicitly checking the type of one of the enum values:
>>> print(type(QTextDocument.FindBackward))
<class 'PyQt5.QtGui.QTextDocument.FindFlag'>

Or you can just look up the relevant enum in the docs: QTextDocument.


Q: changing React.js form values from a chrome extension I'm not developing in React.js, but I'm working on a chrome extension that needs to programatically fill form values for different kinds of sites.
The site uses React.js, and I'm filling the value in the usual way with:
element = document.querySelector("input[name=firstName]");
element.value = "something";

When the user clicks the submit button, he gets this error for that form element, even if the element has a value:
"This information is required."
It doesn't help if fire "change" event for that element.
evt = document.createEvent("HTMLEvents");
evt.initEvent("change", false, true);
element.dispatchEvent(evt);

There is some method in the React.js framework I need to call to programatically change the value? Help from React.js experienced users is appreciated!

A: I found a solution. Call element.select(); before changing the value.


Q: Merge specific keys in a multidimensional array into one-dimensional array I have a complex data that structure I want to simplify.
This array depth may change since it's dynamic data coming from external resource.
I want to merge all arrays that has key price into one dimensional array.
I want to turn this:
array(
    'first_name' => 'John',
    'last_name'  => 'Due',
    'product'    => array(
        'title'   => 'Product #1',
        'price'   => '90',
        'product' => array(
            'title'   => 'Product #2',
            'price'   => '90',
            'product' => array(
                'title' => 'Product #3',
                'price' => '90',
            ),
        ),
    ),
    'misc'       => array(
        'country' => 'United States',
        array(
            'product' => array(
                'title' => 'Product #4',
                'price' => '90',
            ),
        )
    ),
    array(
        'title' => 'Product #5',
        'price' => '90',
    )
);

Into this:
array(
    array(
        'title' => 'Product #1',
        'price' => '90',
    ),
    array(
        'title' => 'Product #2',
        'price' => '90',
    ),
    array(
        'title' => 'Product #3',
        'price' => '90',
    ),
    array(
        'title' => 'Product #4',
        'price' => '90',
    ),
    array(
        'title' => 'Product #5',
        'price' => '90',
    ),
);

I thought a simple way to do it would be using array_walk_recursive, but found I cannot access the parent array.
array_walk_recursive(
    $array,
    function( $value, $key ) {
        if ( 'price' === $key ) {
            // cannot access the parent array
        }
    }
);

A:
$array = array(
    'first_name' => 'John',
    'last_name' => 'Duei',
    'product' => array(
        'title' => 'Product #1',
        'price' => '90',
        'product' => array(
            'title' => 'Product #2',
            'price' => '90',
            'product' => array(
                'title' => 'Product #3',
                'price' => '90',
            ),
        ),
    ),
    'misc' => array(
        'country' => 'United States',
        array(
            'product' => array(
                'title' => 'Product #4',
                'price' => '90',
            ),
        )
    ),
    array(
        'title' => 'Product #5',
        'price' => '90',
    )
);

function array_walk_recursive_full($array, $callback)
{
    if (!is_array($array)) return;

    foreach ($array as $key => $value) {
        $callback($value, $key);
        array_walk_recursive_full($value, $callback);
    }
}

$result = [];

array_walk_recursive_full(
    $array,
    function ($value, $key) use (&$result) {
        if (isset($value['price'])) {
            $result[] = [
                'title' => $value['title'],
                'price' => $value['price'],
            ];
        }
    }
);

print_r($result);

working code example here


Q: Redirect a php script after sending header I have an html page with a form and a submit button.
Once I click submit all the form data, thanks to fpdf, gets turned into pdf.
This pdf is sent without problems to my email.
Building this little page everything always worked without problems and I was able to redirect my user to a thank you page without problems with this code:
header("Location: /thank-you.php",303);
exit();

As soon as I've implemented the pdf file save the final redirection stopped working.
I've implemented the pdf save easily with fpdf:
$pdf->Output("filename.pdf", "D");

And reading on stackoverflow and all the internet I've understood that you can't send two headers.
I thought about solving the problem with javascript so I put after the pdf generation
echo "<script language=javascript>
window.location = 'thanks.html'
</script>";

but no luck.
The php page simply "stops" when the browser downloads the pdf file.
Any chance to solve this?
EDIT:
All the suggestion I got (thanks to everybody) get me to the same point: use thank you page to handle the pdf save.
Sounds great to me.
I've tried preparing a thankyou.php page with a simple $pdf->Output(); in it.
It didn't work...
So I thought to use an include to my create.php (where happens all the magic: pdf creation, email sending, insert into db etc) with:
<?php
include("create.php");
$pdf->Output();
?>

Still no luck.
What's wrong with my thinking?

A: You should approach this the other way around.
Send the user to the thanks page, and on that thanks page do $pdf->Output(). That should do what you want.

A: Webpages/HTTP is a request-response system. The browser sends one request, to which there's exactly one response. You simply cannot respond with a PDF and a redirect, or a PDF and some Javascript.
The typical thing to do is to display the Thank You page first, then inside this page redirect to the file download using Javascript. That way the page stays up and the file downloads.

A: You can make thank-you.php send the PDF file. After submitting the form, send the user to the thank-you page then the thank you page will send the user the PDF file. In that way, the thank you page is visible and the page will still be visible after downloading the PDF file.


Q: vim: NERDTree how to: create/rename/move file/directory I checked the documentation of NERDTree, but didn't find the way to create new file/directory or rename/move it (once I'm browsing directory tree).
In the netrw plugin it would be easy, but this one is not used any more as NERDTree just replaced it. And I don't want to look back.
Anyone ready to point me to the right direction?

A: It's a little bit hidden behind a menu (see :help NERDTreeMenu), but as an upside it is extensible. It is launched (for the current file node) with the m key by default.

The script comes with two default menu plugins: exec_menuitem.vim and
fs_menu.vim. fs_menu.vim adds some basic filesystem operations to the menu for
creating/deleting/moving/copying files and dirs. exec_menuitem.vim provides a
menu item to execute executable files.


Q: Cannot open website link in J2ME I am working on a simple J2ME application and i have  a StringItem linked to a terms and conditions page online.
I have the StringItem setup and it appears underlined (giving the feeling that it is linked); but when i click on it, it does not perform any action.
Find below my code:
public class mobiMidlet extends MIDlet implements CommandListener {

    private Display display;
    private TextField userName,password;
    public Form form;
    private Command login, register, forgot, terms, cancel;
    private Image img_error, img_login, img_register, img_forgot, img_terms;
    private String termsurl = "http://example.com/terms.php";
    private StringItem termsItem;

    public mobiMidlet() {
          form = new Form("Welcome to My App");

          termsItem = new StringItem("", "Terms and Conditions", Item.HYPERLINK);
          termsItem.setDefaultCommand(new Command("terms", Command.ITEM, 1));

            ItemCommandListener listener = new ItemCommandListener() {
                    public void commandAction(Command cmd, Item item) {
                        if(cmd==terms)
                        {
                            try {
                                platformRequest(termsurl);
                            } catch (Exception e) {
                                e.printStackTrace();
                            }
                        }
                    }
                };

            termsItem.setItemCommandListener(listener);

          userName = new TextField("LoginID:", "", 30, TextField.ANY);
          password = new TextField("Password:", "", 30, TextField.PASSWORD);
          cancel = new Command("Cancel", Command.CANCEL, 2);
          login = new Command("Login", Command.OK, 2);
          try{
            img_login = Image.createImage("/logo.jpg");
            img_register = Image.createImage("/error2.png");
            img_forgot = Image.createImage("/logo.jpg");
            img_register = Image.createImage("/error2.png");
          }catch(Exception e){
            System.out.println(e.getMessage());
          }
    }

    public void startApp() {
          display = Display.getDisplay(this);
          form.append(termsItem);
          form.append(userName);
          form.append(password);
          form.addCommand(cancel);
          form.addCommand(login);
          form.setCommandListener(this);
          display.setCurrent(form);
    }

    public void commandAction(Command c, Displayable d) {
          String label = c.getLabel();
          if(label.equals("Cancel")) {
              destroyApp(true);
          } else if(label.equals("Login")) {
            validateUser(userName.getString(), password.getString());
          }
    }
}

How can I fix this so that when I click on the terms and conditions link, it opens the page on a browser?

A: You have not initialized variable terms, so it remains null. Therefore condition cmd==terms is always false and you never enter the if statement.
Separate line termsItem.setDefaultCommand(new Command("terms", Command.ITEM, 1)); to two:
terms = new Command("terms", Command.ITEM, 1);
termsItem.setDefaultCommand(terms);

Now you have a chance.
BTW why not to debug you program? Run it in emulator, put break point into commandAction and see what happens.


Q: Any way to run an internal python script from a webpage? I finally made a project that I wanted to make since a long time :
I'm using an Arduino Uno to replace my PC power button (with a simple relay) and that Arduino Board is connected to a Raspi 3 for network connection purposes
My wish is to do a webpage (or a API-Like request) that at a touch of a button (preferably in a password-protected page) It'll power the PC on
I know how to code in Python, and my script to control the Arduino is already done but I can't find a way to run, only server-side, a Python Script from a button in a webpage
I found that CherryPy framework but I don't think it'll suit my needs
Can someone give me any ideas about that please?

A: As already mentioned by @ForceBru, you need a python webserver.
If this can be useful to you, this is a possible unsecure implementation using flask:
from flask import Flask
from flask import request

app = Flask(__name__)

@app.route('/turnOn')
def hello_world():
    k = request.args.get('key')
    if k == "superSecretKey":
        # Do something ..
        return 'Ok'
    else:
        return 'Nope'

If you put this in an app.py name file and, after having installed flask (pip install flask), you run flask run you should be able to see Ok if visiting the url http://localhost:5000/turnOn?key=superSecretKey .
You could write a brief html gui with a button and a key field in a form but I leaves that to you (you need to have fun too!).
To avoid potential security issues you could use a POST method and https.
Look at the flask documentation for more infos.


Q: Using MultiValuedMap with Jackson Hello I am trying to create an object from the following json :
    {
    "property1": "value1",
    "property2": [
        {"key1":"value1"},
        {"key1":"value2"},
        {"key2":"value1"}
    ]
}

The reason am using MultiValuedMap is because the keys in property 2 can be duplicates (as for the values).
The problem is that jackson throws an error when I try something like this :
@AllArgsConstructor
@NoArgsConstructor
@Data
@Builder
@EqualsAndHashCode
@JsonInclude(JsonInclude.Include.NON_NULL)
public class MyClass {

    private String property1;

    private List<MultiValuedMap<String, String>> property2;

}

As for the controller it's like this :
@PostMapping(value = "update")
MyClass saveMyClass(@RequestBody @Valid MyClass myClass);

but when trying to send the json to my api it gives the following error :

org.springframework.http.converter.HttpMessageConversionException:
Type definition error: [simple type, class
org.apache.commons.collections4.MultiValuedMap]; nested exception is
com.fasterxml.jackson.databind.exc.InvalidDefinitionException: Cannot
construct instance of org.apache.commons.collections4.MultiValuedMap
(no Creators, like default constructor, exist): abstract types either
need to be mapped to concrete types, have custom deserializer, or
contain additional type information

A: Why not just use a List<Map.Entry<String,String>> ?
This works right out of the box and if you really want to use a MuliValuedMap you can convert the List into one with the following sniped:
var map = new ArrayListValuedHashMap<String, String>();
result.property2.stream()
                        .collect(Collectors.groupingBy(Map.Entry::getKey))
                        .entrySet()
                        .forEach(entry ->
                                         map.putAll(entry.getKey(),
                                                    entry.getValue().stream().map(Map.Entry::getValue).toList()));


Q: Closest point from List for every point of other List I have a population of so called "Dots" that search for food. Every Dot has a sight_ value, which indicates the range in which it can see food.
The position of each Dot is saved as a pair<uint16_t,uint16_t>. The positions of all foodsources are in a vector<pair<uint16_t,uint16_t>>.
Now I want to calculate the closest foodsource for every Dot, which this Dot can see. And I don't want to calculate the distance of every combination.
My idea was to create a copy of the food-vector, sort one copy by x and the other by y. Then find the interval [x-sight, x+sight] respectively [y-sight, y+sight] in the vectors and then create the intersection of both.
I've read over set_intersection, but it requires both ranges to be sorted with the same rule.
Any Ideas how I could do this? Could also be that my Idea is just the wrong approach.
Thanks
IceFreez3r
Edit:
I did some runtime approximations:
Sort Food: n log n
Find Interval for one Coordinate and one Dot: 2 log n (lower and upper bound)
If we assume equal distribution of food sources, we can calculate the bound that is estimated to be closer to the middle first and then calculate the second bound in the rest interval. This would reduce the runtime to: log n + log(n/2) (Just realized this s probably not *that* powerful:log(n/2) =~ log(n) - 1)
Build intersection: #x * #y =~ (n * sight/testgroundsize)^2
Compute exact Distance for every Food in Intersection: n * (sight/testgroundsize)^2
Sum: 2 n log n + 2 * #Dots * (log n + log(n/2) + (n * sight/testgroundsize)^2 + n * (sight/testgroundsize)^2)
Sum with just limiting one coordinate: n log n + #Dots * (log n + log(n/2) + n * sight/testgroundsize)
I did some tests and just calculated the above formulas on the run:
int dots = dots_.size();
int sum = 2 * n * log(n) + 2 * dots * (log(n) + log(n/2) + pow(n * (sum_sight / dots) / testground_size_,2) + n * pow((sum_sight / dots) / testground_size_, 2));
int sum2 = n * log(n) + dots * (log(n) + log(n/2) + n * (sum_sight / dots) / testground_size_);
cout << n*dots << endl << sum << endl << sum2 << endl;

It turned out the Intersection idea is just bad. While the idea of just limiting one coordinate is at least better than brute-force.
I didn't think about the grid-idea yet @Daniel Jour

A: You're stepping into a whole field of interesting approaches to this problem. Terms to Google are binary space partitioning, quadtrees, ... and of course nearest neighbour search.
A relatively simple but effective approach when the dots are far more spread than what their "visible range" is:

*

*Select a value "grid size".

*Create a map from grid coordinates to a list/set of entities

*For each food source:  put them in the map at their grid coordinates

*For each dot: put them in the map at their grid coordinates and also in the neighbour grid "cells". The size of the neighbourhood depends on the grid size and the dot's sight value

*For each entry in the map which contains at least one dot: Either do this algorithm recursively with a smaller grid size or use the brute force approach: check each dot in that grid cell against each food source in that grid cell.

This is a linear algorithm, compared with the quadratic brute force approach.
Calculation of grid coordinates: grid_x = int(x / grid_size) ... same for other coordinate.
Neighbourhood: steps = ceil(sight_value / grid_size) .. the neighbourhood is a square with side length 2×steps + 1 centred at the dot's grid coordinates

A: I believe your approach is incorrect. This can be mathematically verified. What you can do instead is calculate the magnitude of the vector joining the dot with the food source by means of Pythagoras theorem, and ensure that this magnitude is less than the observation limit. This deals exclusively with determining relative distance, as defined by the Cartesian co-ordinate system, and the standard unit of measurement. In relation to efficiency concerns, the first order of business is to determine if the approach to be taken is in computational terms in actuality less efficient, as measured by time, even though the logical component responsible for certain calculations are, in virtue of this alternative implementation, less time consuming. Of coarse, the ideal is one in which the time taken is decreased, and not merely numerically contained by means of refactoring.
Now, if it is the case that the position of a dot can be specified as any two numbers one may choose, this of course implies a frame of reference called the basis, and also one local to the dot in question. With respect to both, one can quantify position, and other such characteristics and properties. As a consequence of this observation, it would seem that you need n*2 data structures, where n is the amount of dots in the environment, that
contain the sorted values relative to each dot, and quite frankly it is unclear whether or not this approach would even work or is optimal. You state the design and programmatic constraint that the solution shall not compute the distances from each dot to each food source. But to achieve this, one must implement other such procedures, in order that we derive the correct results. These comments are made in relation to my discussion on efficiency. Therefore, you may be better of simply calculating the distance in each case. This is somewhat elegant.


Q: Can you append strings to variables in PHP? Why does the following code output 0?
It works with numbers instead of strings just fine. I have similar code in JavaScript that also works. Does PHP not like += with strings?
<?php
    $selectBox = '<select name="number">';
    for ($i=1; $i<=100; $i++)
    {
        $selectBox += '<option value="' . $i . '">' . $i . '</option>';
    }
    $selectBox += '</select>';

    echo $selectBox;
?>

A: In PHP use .= to append strings, and not +=.

Why does this output 0? [...] Does PHP not like += with strings?

+= is an arithmetic operator to add a number to another number. Using that operator with strings leads to an automatic type conversion. In the OP's case the strings have been converted to integers of the value 0.

More about operators in PHP:

*

*Reference - What does this symbol mean in PHP?

*PHP Manual – Operators

A: PHP syntax is little different in case of concatenation from JavaScript.
Instead of (+) plus a (.) period is used for string concatenation.
<?php

$selectBox = '<select name="number">';
for ($i=1;$i<=100;$i++)
{
    $selectBox += '<option value="' . $i . '">' . $i . '</option>'; // <-- (Wrong) Replace + with .
    $selectBox .= '<option value="' . $i . '">' . $i . '</option>'; // <-- (Correct) Here + is replaced .
}
$selectBox += '</select>'; // <-- (Wrong) Replace + with .
$selectBox .= '</select>'; // <-- (Correct) Here + is replaced .
echo $selectBox;

?>

A: This is because PHP uses the period character . for string concatenation, not the plus character +. Therefore to append to a string you want to use the .= operator:
for ($i=1;$i<=100;$i++)
{
    $selectBox .= '<option value="' . $i . '">' . $i . '</option>';
}
$selectBox .= '</select>';


Q: Pandas Dataframe sum row based on column header I have the following dataframe and want to create two columns, one will show the amount MTD and the other will show the cumulative YTD based on a date parameter for each Account Name. This is easily achievable in Excel using a =SUMIFS formula and want to know the Python equivalent.
+---------------+------------+------------+------------+------------+
| Account Names | 31/01/2022 | 28/02/2022 | 31/03/2022 | 30/04/2022 |
+---------------+------------+------------+------------+------------+
| Cash At Bank  |        100 |        150 |        100 |        150 |
| Debtors       |         50 |         50 |         50 |        100 |
| Inventory     |        250 |        250 |        350 |        100 |
| PAYG Withheld |         50 |         50 |         10 |        150 |
+---------------+------------+------------+------------+------------+

Ideally, I'd want this to be as efficient as possible i.e. doesn't require loops. I went the route of trying to do this using np.select as I've read this is one of the fastest methods, but had no luck. I get the following error:

ValueError: shape mismatch: objects cannot be broadcast to a single shape

EndDate = '31/03/2022'
Budget_Assets["MTD_Amount"] = np.select(condlist=[Budget_Assets.columns == EndDate],choicelist=[Budget_Assets[EndDate]],default=0)

For example, the value in the MTD_Amount column for Cash At Bank should be 100 and the YTD_Column will be 350 (sum of numbers from '31/01/2022' to '31/03/2022')

A: You can try sum(axis=1) by slicing the datetime like columns to calculate YTD and just use loc to get MTD
EndDate = '31/03/2022'
date_cols = df.filter(regex='\d{2}/\d{2}/\d{4}')
date_cols.columns = pd.to_datetime(date_cols.columns, dayfirst=True)

df['YTD_Column'] = date_cols.loc[:, :pd.to_datetime(EndDate, dayfirst=True)].sum(axis=1)
df['MTD_Column'] = df[EndDate]

   Account Names  31/01/2022  28/02/2022  31/03/2022  30/04/2022  YTD_Column  MTD_Column
0   Cash At Bank         100         150         100         150         350         100
1        Debtors          50          50          50         100         150          50
2      Inventory         250         250         350         100         850         350
3  PAYG Withheld          50          50          10         150         110          10


Q: Firefox Password Field is not empty I'm new here on stackoverflow.
I'm writing a Form to add a Album to a gallery, but now I discovered a problem in Firefox which I've never had. The password field is already set. I never filled out the form.
Does somebody knows, why Firefox fills text in?

A: If it is a saved password, you will be able to find it in the security and password settings (see link for more information).  If you've saved a password on a different portion of the site (say you have a form on www.site.com/login.html and www.site.com/admin.html for example), it could be pulling it from there.


Q: Can you use "first class" concept on Python methods/attributes? Can the "first-class" concept be applied to Python methods/attributes like it can functions?
>>>a=sum
>>>a([1,2,3])
6

I would like to do something like:
>>>case='lower'
>>>'UPPERCASE'.case()

To produce the string object 'uppercase'. Otherwise, would I just have to use eval?

A: You can do it this way:
case = str.lower # Take the lower() method of the str class.
case('UPPERCASE') # pass your string as the first argument, which is self.

In this case, Python being explicit about self being the first argument to methods makes this a lot clearer to understand.


Q: How to Reduce 3G data consumption using Google Map API for Android I am developing an android application that requires to display the current location of a user and to load KMZ file (with poly lines) on Google Map (use of google map api).
My application opens the google map, loads the KMZ file and diplays current position fast, when having wi-fi and 3G enabled to mobile.The problem I face is that having 3G the data consumption is too big. I checked that after 5 clicks/zoom in-out on a single map the data consumption on mobile become 100MB..
Are there any ways to reduce the 3G data consumption? Should I use another map source?
Thanks


Q: How to remap the copy-paste keyboard shortcuts in MATLAB on Ubuntu? The default keys are alt-w for copying and ctrl-y for pasting. Is there any way to remap this to ctrl-c for copying and ctrl-v for pasting?

A: Yes. Go to Preferences -> Keyboard.
There you will find "Command Window keybindings" and "Editor/Debugger" keybindings.
These are most likely set to "Emacs" style for you -- you should change them to "Windows" style to copy and paste with Ctrl-C and Ctrl-V, respectively.
Source: http://blogs.mathworks.com/community/2007/05/11/setting-up-keybindings-for-the-command-window-and-editor/

A: In Matlab version R2020a, you can change the keyboard shortcuts by following these steps:

*

*Go to Home > Preferences > Keyboard > Shortcuts

*Change the Active Settings to Windows Default Set

*Apply the changes by clicking on Apply and then Ok
It will look like this screenshot.

Now you can use ctrl-C / ctrl-V to copy / paste as usual.


Q: Google breakpad crashes when run under a debugger We have a problem where initializing the Google Breakpad exception handler errors out when the program is run under lldb, but not when run normally from the shell.
The system is MacOS 13 (Ventura) and the IDE is Visual Studio Code.
The code below fails on a call to init():
namespace crashhandler {
    static std::unique_ptr<google_breakpad::ExceptionHandler> pExceptionHandler;

    namespace {
        bool DumpCallback(const char* dump_dir, const char* minidump_id, void*, bool success) {
            if (success)
                printf("Application crashed. Breakpad Crash Handler created a dump at location %s/%s.dmp\n",
                       dump_dir, minidump_id);
            else
                printf("Application crashed. Breakpad Crash Handler failed to create a dump");

            fflush(stdout);
            return success;
        }
    } // namespace

    void init(const std::string& reportPath) // <-- crash happens when calling this function
    {
        if (pExceptionHandler)
            return;
        pExceptionHandler.reset(
            new google_breakpad::ExceptionHandler(reportPath, nullptr, DumpCallback, nullptr, true, nullptr));
    }
} // namespace crashhandler

The debug console shows:
=================================================================
==5060==ERROR: AddressSanitizer: stack-buffer-underflow on address 0x00016fdfee00 at pc 0x000100ac9030 bp 0x00016ff11540 sp 0x00016ff10d08
READ of size 4608 at 0x00016fdfee00 thread T2
    #0 0x100ac902c in wrap_write+0x15c (libclang_rt.asan_osx_dynamic.dylib:arm64e+0x1902c)
    #1 0x100109f08 in google_breakpad::UntypedMDRVA::Copy(unsigned int, void const*, unsigned long)+0x54 (my_server:arm64+0x100109f08)
    #2 0x10010ce14 in google_breakpad::MinidumpGenerator::WriteStackFromStartAddress(unsigned long long, MDMemoryDescriptor*)+0xf8 (my_server:arm64+0x10010ce14)
    #3 0x10010d244 in google_breakpad::MinidumpGenerator::WriteThreadStream(unsigned int, MDRawThread*)+0x100 (my_server:arm64+0x10010d244)
    #4 0x10010c04c in google_breakpad::MinidumpGenerator::WriteThreadListStream(MDRawDirectory*)+0xfc (my_server:arm64+0x10010c04c)
    #5 0x10010bd20 in google_breakpad::MinidumpGenerator::Write(char const*)+0xc8 (my_server:arm64+0x10010bd20)
    #6 0x10010adc0 in google_breakpad::ExceptionHandler::WriteMinidumpWithException(int, int, int, __darwin_ucontext64*, unsigned int, bool, bool)+0x160 (my_server:arm64+0x10010adc0)
    #7 0x10010af1c in google_breakpad::ExceptionHandler::WaitForMessage(void*)+0x104 (my_server:arm64+0x10010af1c)
    #8 0x1a330a068 in _pthread_start+0x90 (libsystem_pthread.dylib:arm64e+0x7068)
    #9 0x1a3304e28 in thread_start+0x4 (libsystem_pthread.dylib:arm64e+0x1e28)

Address 0x00016fdfee00 is located in stack of thread T0 at offset 0 in frame
    #0 0x1000034cc in main main.cpp:36

  This frame has 10 object(s):
    [32, 56) 'reportPath' (line 39) <== Memory access at offset 0 partially underflows this variable
    [96, 120) 'ref.tmp' (line 40) <== Memory access at offset 0 partially underflows this variable
    [160, 208) 'parser' (line 43) <== Memory access at offset 0 partially underflows this variable
    [240, 264) 'configPath' (line 45) <== Memory access at offset 0 partially underflows this variable
    [304, 320) 'ref.tmp12' (line 46) <== Memory access at offset 0 partially underflows this variable
    [336, 360) 'agg.tmp' <== Memory access at offset 0 partially underflows this variable
    [400, 416) 'ref.tmp30' (line 57) <== Memory access at offset 0 partially underflows this variable
    [432, 456) 'agg.tmp42' <== Memory access at offset 0 partially underflows this variable
    [496, 520) 'agg.tmp80' <== Memory access at offset 0 partially underflows this variable
    [560, 568) 'ref.tmp86' (line 74) <== Memory access at offset 0 partially underflows this variable
HINT: this may be a false positive if your program uses some custom stack unwind mechanism, swapcontext or vfork
      (longjmp and C++ exceptions *are* supported)
SUMMARY: AddressSanitizer: stack-buffer-underflow (libclang_rt.asan_osx_dynamic.dylib:arm64e+0x1902c) in wrap_write+0x15c
Shadow bytes around the buggy address:
  0x00702dfdfd70: 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00
  0x00702dfdfd80: 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00
  0x00702dfdfd90: 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00
  0x00702dfdfda0: 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00
  0x00702dfdfdb0: 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00
=>0x00702dfdfdc0:[f1]f1 f1 f1 00 00 00 f2 f2 f2 f2 f2 f8 f8 f8 f2
  0x00702dfdfdd0: f2 f2 f2 f2 f8 f8 f8 f8 f8 f8 f2 f2 f2 f2 f8 f8
  0x00702dfdfde0: f8 f2 f2 f2 f2 f2 f8 f8 f2 f2 00 00 00 f2 f2 f2
  0x00702dfdfdf0: f2 f2 f8 f8 f2 f2 00 00 00 f2 f2 f2 f2 f2 00 00
  0x00702dfdfe00: 00 f2 f2 f2 f2 f2 f8 f3 f3 f3 f3 f3 00 00 00 00
  0x00702dfdfe10: 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00
Shadow byte legend (one shadow byte represents 8 application bytes):
  Addressable:           00
  Partially addressable: 01 02 03 04 05 06 07
  Heap left redzone:       fa
  Freed heap region:       fd
  Stack left redzone:      f1
  Stack mid redzone:       f2
  Stack right redzone:     f3
  Stack after return:      f5
  Stack use after scope:   f8
  Global redzone:          f9
  Global init order:       f6
  Poisoned by user:        f7
  Container overflow:      fc
  Array cookie:            ac
  Intra object redzone:    bb
  ASan internal:           fe
  Left alloca redzone:     ca
  Right alloca redzone:    cb
Thread T2 created by T0 here:
    #0 0x100ae8c5c in wrap_pthread_create+0x54 (libclang_rt.asan_osx_dynamic.dylib:arm64e+0x38c5c)
    #1 0x10010a360 in google_breakpad::ExceptionHandler::Setup(bool)+0xd0 (my_server:arm64+0x10010a360)
    #2 0x10010a1c4 in google_breakpad::ExceptionHandler::ExceptionHandler(std::__1::basic_string<char, std::__1::char_traits<char>, std::__1::allocator<char> > const&, bool (*)(void*), bool (*)(char const*, char const*, void*, bool), void*, bool, char const*)+0x110 (my_server:arm64+0x10010a1c4)
    #3 0x1001132b4 in crashhandler::init(std::__1::basic_string<char, std::__1::char_traits<char>, std::__1::allocator<char> > const&)+0x58 (my_server:arm64+0x1001132b4)
    #4 0x10000367c in main main.cpp:41
    #5 0x1a2fdfe4c  (<unknown module>)

==5060==ABORTING

To reiterate, if I run the program outside of the debugger, it proceeds normally.
What can cause this?

A: Breakpad is inserting a right into the process's "task exception port" - which is where you listen for crashes and the like either from within the process or externally - i.e. when you are a debugger.  But in Mach the exception ports only have a single owner.  So when you run under the debugger, Breakpad and the debugger fight for control of the exception port.  For example, if you got your port right set up before the debugger attached, you will end up with a bad port right after the attach, because lldb now owns the port.
Debugging programs that use task exception port handlers is not well supported, because (a) it would be tricky to get that right and (b) there aren't enough programs that need to do this to motivate the effort (at least on the debugger side).  Most people turn off their exception handling for their debug builds since their exception catcher and the debugger are pretty much doing the same job, and it's more convenient to trap in the debugger than the internal exception handler.  And the core part of the exception handler is usually simple enough that you can do printf debugging if you really need to debug that part.


Q: Symfony 2 - Form collection for one entity without parent entity I have problem with form collection. I want to show one form with all values from one entity and I want to be able to add or remove some record(line) from this entity on one page. I have the following solutions, which is ok.
CurrencyController
class CurrencyController extends Controller {
/**
 * @Template()
 */
public function testAction() {
    $em = $this->getDoctrine()->getManager();

    $currencies = $em->getRepository('MyWebBundle:Currency')->findAll();

    $arr = array('currencies' => $currencies);
    $form = $this->createFormBuilder($arr)
    ->add('currencies', 'collection', array(
    'type' => new CurrencyType(),
                'allow_add'    => true,
                'allow_delete'    => true,
                'by_reference' => false,
    ))
    ->add('submit', 'button', array('label' => 'Odeslat'))
    ->getForm();

    return array(
        'form' => $form->createView(),
    );
}
}

CurrencyType
class CurrencyType extends AbstractType {

/**
 * @param FormBuilderInterface $builder
 * @param array $options
 */
public function buildForm(FormBuilderInterface $builder, array $options) {
    $builder
            ->add('abbreviation', 'text')
            ->add('rate', 'number')
    ;
}

/**
 * @param OptionsResolverInterface $resolver
 */
public function setDefaultOptions(OptionsResolverInterface $resolver) {
    $resolver->setDefaults(array(
        'data_class' => 'My\WebBundle\Entity\Currency'
    ));
}

/**
 * @return string
 */
public function getName() {
    return 'currency';
}
}

Twig
{% extends '::base.html.twig' %}

{% block body -%}

Test

{{ form(form) }}

{% endblock %}

If I use form class for CurrenciesType, then Symfony throws exception
Notice: Object of class My\WebBundle\Entity\Currency could not be converted to int in
....\web\vendor\symfony\symfony\src\Symfony\Component\
Form\Extension\Core\ChoiceList\ChoiceList.php line 462

Code for this is below.
CurrencyController
class CurrencyController extends Controller {
/**
 * @Template()
 */
public function testAction() {
    $em = $this->getDoctrine()->getManager();

    $currencies = $em->getRepository('MyWebBundle:Currency')->findAll();

    $arr = array('currencies' => $currencies);
    $form = $this->createForm(new CurrenciesType(), $arr);

    return array(
        'form' => $form->createView(),
    );
}
}

CurrenciesType
class CurrenciesType extends AbstractType {

/**
 * @param FormBuilderInterface $builder
 * @param array $options
 */
public function buildForm(FormBuilderInterface $builder, array $options) {
    $builder
            ->add('currencies', 'collection', array(
                'type' => new CurrencyType(),
                'allow_add' => true,
                'allow_delete' => true,
                'by_reference' => false,
            ))
            ->add('submit', 'button', array('label' => 'Send'))
    ;
}

/**
 * @param OptionsResolverInterface $resolver
 */
public function setDefaultOptions(OptionsResolverInterface $resolver) {
    $resolver->setDefaults(array(
        'data_class' => null
    ));
}

/**
 * @return string
 */
public function getName() {
    return 'my_webbundle_currencies';
}
}

CurrencyType and Twig are same as above.
I found solution these solution #1 solution #2, but my symfony still throws exception as above and I don't see different in my solution and these solutions. Please help with this problem. Thank you all :)


Q: How to set the color of margins in a QGridLayout? How to set the color of margins in a QGridLayout? I want to show the different columns and rows separately by placing lines between various rows and columns.
In other words, how to display items in grid-layout such that they are in a table.

A: QGridLayout doesn't draw anything, it just calculates the layout. So the QGridLayout itself cannot draw gridlines for you.
The easiest way is to put a QFrame to each of your QGridLayout's cell and move your content to these QFrames. In WinXP, setting QFrame's frameShape to Box and frameShadow to Plain, you get simple boxes.
You could also create a new widget that draws the gridlines according to the layout that the QGridLayout calculates. By using QGridLayout::itemAtPosition you can get a QLayoutItem for each cell.


Q: MySQL table with a lot of text So I have this database (Size 3.1Gb total), but this is due to one specific table I've got, containing A LOT of console output text, from some test runs. The table itself is 2.7Gb, and I was wondering if there could be another solution for this table, so the database would get a lot smaller? It's getting a bit anoying to backup the database or even make a copy of the database to a playground, because it's so big this table.
The Table is this one

Would it be better to delete this table and make all the LogTextData <- LongText, be stored in a PDF, instead of the database? (Then I can't backup this data tho...)
Do anyone have an idea on how to make this table smaller, or another solution? I'm open for suggestions, to make this table smaller.
The way this console log data gets imported to the database is by Python scipts, so I have fully access to other python solutions, if there is any.

A: You could try enabling either the Storage-Engine Independent Column Compression or InnoDB page compression. Both provides ways to have a smaller on-disk database which is especially useful for the large text fields.
Since there's only one table with one particular field that's taking up space, trying out individual column compression seems like the easiest first step.

A: According to me you should just store the path of log files instead of the complete logs in the database. By using those paths you can access the files anytime you want.
It will decrease the size of database too.
Your new table would look like this,
LogID, BuildID, JenkinsJobName,LogTextData.


Q: How to set dashed axes on a box plot I would like to figure out if it is possible using pyplot setting a dashed box (I mean the axes of plot contours) of the plot.
I know that could sound strange and horrible. but I would like to try using it.

A: The axes "box" consists of 4 "spines", which are accessible via ax.spines. You may set a linestyle to those as shown below.
import matplotlib.pyplot as plt

fig, axes = plt.subplots(2,2)

linestyles = ["--","-.",":", (0,(5,2,1,4))]

for ax, ls in zip(axes.flat, linestyles):
    for spine in ax.spines.values():
        spine.set_linestyle(ls)
        spine.set_linewidth(2)
    ax.set_title("linestyle: {}".format(ls))

plt.tight_layout()
plt.show()


Q: Having issues with fetching an environment variable In the root of my React project, I have this .env file containing the following.
DS_API_URL=[http://url.com](http:url.com/)

In another file of the project, an axios call utilizes this to return some stuff.
const url = 'http://url.com/graph/tech-stack-by-role' will return what I need.
const url = `${DS_API_URL}/graph/tech-stack-by-role`; returns an error.
How do I fetch the link from the env file and assign it to a var?

A: To use environment variable in react you need to prefix the variable name with process.env.REACT_APP_. Documentation
So in your .env file you have:
REACT_APP_DS_API_URL=[http://url.com](http:url.com/)

Then to use:
const url = `${process.env.REACT_APP_DS_API_URL}/graph/tech-stack-by-role`

Update to answer question:
update your start script to use the .env file you want. in this case it is .env.localhost. You will also need to npm install or yarn install env-cmd:
"start": "env-cmd -f ./.env.localhost react-scripts start",


Q: Capture 2nd entry from database I'm quite new to the programming world and have become stuck with querying a database in C#.
I am trying to return a date and an Int32 from the second entry in a database using the code below:
OleDbCommand com101 = new OleDbCommand("SELECT TOP 2 [Flight_Date], [No_Launches] FROM Flights WHERE [Claimed_By_ID] = ? ORDER BY [Flight_Date] DESC LIMIT 1,1", Program.DB_CONNECTION);
com101.Parameters.Add(new OleDbParameter("", 451));
OleDbDataReader dr101 = com101.ExecuteReader();

when I run the code I get an error saying there is a problem with the Syntax error in ORDER BY clause.
Can anyone spot what I am missing?
Cheers

A: This is your query:
SELECT TOP 2 [Flight_Date], [No_Launches]
FROM Flights
WHERE [Claimed_By_ID] = ?
ORDER BY [Flight_Date] DESC
LIMIT 1,1;

You need to decide which database you are using.  Some support TOP; some support LIMIT.  Based on your error and the use of the square braces, I would guess that you are using SQL Server/Sybase and should remove the LIMIT clause:
SELECT TOP 2 [Flight_Date], [No_Launches]
FROM Flights
WHERE [Claimed_By_ID] = ?
ORDER BY [Flight_Date] DESC;

If this is true, you should change the tag on the question from "mysql" to "sql-server".
EDIT:
To get the second entry, I think you can use a subquery:
SELECT TOP 1 *
FROM (SELECT TOP 2 [Flight_Date], [No_Launches]
      FROM Flights
      WHERE [Claimed_By_ID] = ?
      ORDER BY [Flight_Date] DESC
     ) as t
ORDER BY Flight_Date ASC


Q: Creating an if/elif statement with regex error in python So recently I started learning python through an online education platform and currently I hit a wall.
So the problem is:
Create an if statement that takes an age value. This if statement should print the word “child” if age is 12 or less, “teenager” if age is between 13 and 19 inclusive, and “adult” if age is greater than 19.
and my code is:
age = 16

if age < 13:
    print("child")

elif (age >= 13) and (age < 20):
    print("teenager")

else:
    print("adult")

So according to the website, the part I did for child and adult is correct but the teenager part of it is wrong and is showing this regex message:
Searched your code for a specific pattern:

^elif (13\s*<=\s*age|12\s*<\s*age)?\s*(or|\|)?\s*(age)?(\s*<\s*20|\s*<=\s*19):$\s*print\(('|")teenager('|")\)

So I basically tried learning regex to understand what I did wrong and what I could understand from it is basically but I'm sure that I'm reading it wrong:
elif (13 <= age 12 < age) or (age < 20 <= 19):
    print("teenager")

So what am I missing? Any help would be very much appreciated thanks! :)


Q: java.util.NoSuchElementException: No line found* I keep getting this error
java.util.NoSuchElementException No line found
when I use this method
public boolean hasMoreCommands() {
    if (input.hasNextLine()) {
        return true;
    } else {
        //input.close();
        return false;
    }
}

public void advance() {
    String str;
    if(hasMoreCommands() == true){
        do {
            str = input.nextLine().trim();

            // Strip out any comments
            if (str.contains("//")) {
                str = (str.substring(0, str.indexOf("//"))).trim();
            }
        } while (str.startsWith("//") || str.isEmpty() || hasMoreCommands());
        command = str;
  }
}

I have main code here:
public class Ptest
{
  public Ptest(String fileName)
  {
    String line = null;
    String nName = fileName.replace(".vm", ".asm");
    Parser p = new Parser();

    try{
        File neF = new File(nName);
        if(!neF.exists()){
            neF.createNewFile();
        }
        File tempFile = new File("temp.txt");
        if(!tempFile.exists()){
            tempFile.createNewFile();
        }

        FileReader fr = new FileReader(fileName);
        BufferedReader br = new BufferedReader(fr);
        FileWriter fw = new FileWriter(nName);
        BufferedWriter bw = new BufferedWriter(fw);
        FileWriter writR = new FileWriter(tempFile);
        BufferedWriter buffR = new BufferedWriter(writR);
        while((line = br.readLine()) != null) {
            buffR.write(line+ "\n");
            //System.out.println(line);
        }
        buffR.flush();
        buffR.close();
        p.insertTitle(tempFile);
        String ctype = p.commandType();
        int len = ctype.length();
        int spaces = 13 - len;
        String sp = " ";
        String asp = " ";
        String a1 = null;
        int a2;
        int alen;
        boolean t = false;
        while(p.hasMoreCommands()){
            for(int i= 0; i < spaces; i++){
                sp += " ";
            }
            t = p.hasMoreCommands();
            a1 = p.arg1();
            alen = (10 - a1.length());
            for(int i= 0; i < alen; i++){
                asp += " ";
            }
            //a2 = p.arg2();
            if (ctype == "C_PUSH" || ctype == "C_POP" || ctype == "C_FUNCTION" || ctype == "C_CALL") {
                a2 = p.arg2();
                bw.write(ctype + sp + a1 + asp + a2);
            }
            else {
                bw.write(ctype + sp + a1);
            }
            p.advance();
            ctype = p.commandType();
            len = ctype.length();
            spaces = 13 - len;
        }

        bw.flush();
        bw.close();
    }
    catch(FileNotFoundException ex){
        System.out.println("File not found!");
    }
    catch(IOException ex){
        System.out.println("Error reading file '"  + fileName + "'");
    }
  }
}

I went through debugger and it literally goes the entire file then gives me an error when its finished.

A: Like @hfontanez I think your problem is in this code:
if(hasMoreCommands() == true){
    do {
        str = input.nextLine().trim();

        // Strip out any comments
        if (str.contains("//")) {
            str = (str.substring(0, str.indexOf("//"))).trim();
        }
    } while (str.startsWith("//") || str.isEmpty() || hasMoreCommands());
    command = str;
}

However, my solution is to change the while clause to while (str.isEmpty() && hasMoreCommands());
I'm assuming that "advance" ought to return the next non-comment / blank line.
If the string from the previous pass is empty (after stripping any comment) it will go round the loop again provided that wasn't the last line. But, if that was the last line or str still has something in it, then it will exit the loop. Comments should have been stripped so don't need tested for in the while.
I think if you just test for hasNextLine within the loop then it will never exit the loop if the last line was comment / blank.

A: My guess is that your problem is here:
if(hasMoreCommands() == true){
    do {
        str = input.nextLine().trim();

        // Strip out any comments
        if (str.contains("//")) {
            str = (str.substring(0, str.indexOf("//"))).trim();
        }
    } while (str.startsWith("//") || str.isEmpty() || hasMoreCommands());
    command = str;
}

The exception you encountered (NoSuchElementException) typically occurs when someone tries to iterate though something (String tokens, a map, etc) without checking first if there are any more elements to get.  The first time the code above is executed, it checks to see if it has more commands, THEN it gets in a loop.  The first time it should work fine, however, if the test done by the while() succeeds, the next iteration will blow up when it tries to do input.nextLine().  You have to check is there is a next line to be got before calling this method.  Surround this line with an if(input.hasNextLine()) and I think you should be fine.


Q: Axios + Typescript: how to pass a param of type "ResponseType"? Axios defines ResponseType as
export type ResponseType =
  | 'arraybuffer'
  | 'blob'
  | 'document'
  | 'json'
  | 'text'
  | 'stream'

I'm trying to pass a configuration to axios.post
const config = {
        headers: {
            'X-Requested-With': 'XMLHttpRequest',
            'Content-Type': 'application/x-www-form-urlencoded',
            'Host': HOST_HEADER,
        },
        responseType: 'json'
 }

 const data_to_post = { .... omitted ... }

 return axios.post(HOST, data_to_post, config)

Problem: typescript linter warn me saying the type string cannot be assigned to type ResponseType.
Also tried: Of course I cannot use the syntax
 responseType: ResponseType.json

How can I fix this?

A: The problem is that Typescript will infer config to be of type
{
    headers: {
        'X-Requested-With': string;
        'Content-Type': string;
        'Host-Header': string;
    };
    responseType: string;
}

Typescript does not know that you are trying to create a config object for Axios. You can explicitly type the entire object as AxiosRequestConfig, or you could explicitly type responseType: 'json' to be of type ResponseType.
const config: AxiosRequestConfig = {
  headers: {
    'X-Requested-With': 'XMLHttpRequest',
    'Content-Type': 'application/x-www-form-urlencoded',
    'Host-Header': 'dsa',
  },
  responseType: 'json'
};

A: Fixed using explicit casting
responseType: <ResponseType> 'json'