text:
Q: I Would Be Thankful for your Help Today, I tried something new when editing on Stack Overflow. I tried searching for "Thank you in advanced". I found several hundred posts, and got rid of quite a few - anything posted this month, as a matter of fact.
I then tried "Thanks you in advance", and again, got rid the phrase from posts created in December.
I tried "Thank you in advance", and found over 10,000. I got rid of all that I found from today, but they keep coming back.
I tried "Thanks", and was horrified to find millions of them! And there's no way I can even edit the ones created in the past hour!
So, I'd be thankful for your help if you would help me edit some more of these. I'll even "allow" you to use the same ad-hoc comment I use:

Unlike forum sites, we don't use "Thanks", or "Any help appreciated", or signatures on [so]. See [Should 'Hi', 'thanks,' taglines, and salutations be removed from posts?](Should 'Hi', 'thanks', taglines, and salutations be removed from posts?).

Warning: I have also been asked if I'm grumpy today1. I'd like some help before they get around to asking me who peed in my cornflakes.
Thanks,
John Saunders
--
1.Hell no, I'm not grumpy!

Note: I have been improving the whole question. I never make targeted edits only. I always fix all typos, tags in titles, etc. that I see.

Note carefully: I am not advocating a mass campaign to remove only the salutations. I, personally, never do that, unless the salutation is the only thing wrong with the post.
I am trying to point out that we're leaving a lot of these minor "broken windows" and "litter" hanging around, and I'd like us to start doing better at cleaning them up. That is, cleaning them up, in addition to whatever else is wrong with the post.
I'm also advocating leaving a comment telling the OP why the edit is done. I believe that will not only be good for the OP, but for others who will read the comment and decide not to leave a salutation to begin with.

P.S. The "Thanks" in this post is meant to be facetious. Editors, kindly leave it alone.

A: John, I would love to help out some more. I have already done a lot of that while editing new posts that I see come in that need other edits.
I think that there should be a permanent text stating (Do NOT write useless text like: "thanks", "thanks in advance", "please help", etc). This text should be placed as a div over the question input field and should not be removed until the user clicks an Ok, I won't button. Once they've asked 5 questions and clicked Ok, I won't button those 5 times, then it shouldn't appear anymore for that user.

A: If you only remove salutations then theses are unnecessary minor edits.
Every post you edit gets pushed in the active questions queue. So mass edits should have a good reason and removing just thank you without improving the whole post is not really helpful.


text:
Q: Reading the target of a .lnk file in Python? I'm trying to read the target file/directory of a shortcut (.lnk) file from Python. Is there a headache-free way to do it? The spec is way over my head.
I don't mind using Windows-only APIs.
My ultimate goal is to find the "(My) Videos" folder on Windows XP and Vista. On XP, by default, it's at %HOMEPATH%\My Documents\My Videos, and on Vista it's %HOMEPATH%\Videos. However, the user can relocate this folder. In the case, the %HOMEPATH%\Videos folder ceases to exists and is replaced by %HOMEPATH%\Videos.lnk which points to the new "My Videos" folder. And I want its absolute location.

A: I also realize this question is old, but I found the answers to be most relevant to my situation.
Like Jared's answer, I also could not use the win32com module.  So Jared's use of the binary structure from MS-SHLLINK got me part of the way there. I needed read shortcuts on both Windows and Linux, where the shortcuts are created on a samba share by Windows.  Jared's implementation didn't quite work for me, I think only because I encountered some different variations on the shortcut format.  But, it gave me the start I needed (thanks Jared).
So, here is a class named MSShortcut which expands on Jared's approach. However, the implementation is only Python3.4 and above, due to using some pathlib features added in Python3.4
#!/usr/bin/python3

# Link Format from MS: https://msdn.microsoft.com/en-us/library/dd871305.aspx
# Need to be able to read shortcut target from .lnk file on linux or windows.
# Original inspiration from: http://stackoverflow.com/questions/397125/reading-the-target-of-a-lnk-file-in-python

from pathlib import Path, PureWindowsPath
import struct, sys, warnings

if sys.hexversion < 0x03040000:
    warnings.warn("'{}' module requires python3.4 version or above".format(__file__), ImportWarning)

# doc says class id =
#    00021401-0000-0000-C000-000000000046
# requiredCLSID = b'\x00\x02\x14\x01\x00\x00\x00\x00\xC0\x00\x00\x00\x00\x00\x00\x46'
# Actually Getting:
requiredCLSID   = b'\x01\x14\x02\x00\x00\x00\x00\x00\xC0\x00\x00\x00\x00\x00\x00\x46'  # puzzling

class ShortCutError(RuntimeError):
    pass

class MSShortcut():
    """
    interface to Microsoft Shortcut Objects.  Purpose:
    - I need to be able to get the target from a samba shared on a linux machine
    - Also need to get access from a Windows machine.
    - Need to support several forms of the shortcut, as they seem be created differently depending on the
      creating machine.
    - Included some 'flag' types in external interface to help test differences in shortcut types

    Args:
        scPath (str): path to shortcut

    Limitations:
        - There are some omitted object properties in the implementation.
          Only implemented / tested enough to recover the shortcut target information. Recognized omissions:
          - LinkTargetIDList
          - VolumeId structure (if captured later, should be a separate class object to hold info)
          - Only captured environment block from extra data
        - I don't know how or when some of the shortcut information is used, only captured what I recognized,
          so there may be bugs related to use of the information
        - NO shortcut update support (though might be nice)
        - Implementation requires python 3.4 or greater
        - Tested only with Unicode data on a 64bit little endian machine, did not consider potential endian issues

    Not Debugged:
        - localBasePath - didn't check if parsed correctly or not.
        - commonPathSuffix
        - commonNetworkRelativeLink

    """

    def __init__(self, scPath):
        """
        Parse and keep shortcut properties on creation
        """
        self.scPath = Path(scPath)

        self._clsid = None
        self._lnkFlags = None
        self._lnkInfoFlags = None
        self._localBasePath = None
        self._commonPathSuffix = None
        self._commonNetworkRelativeLink = None
        self._name = None
        self._relativePath = None
        self._workingDir = None
        self._commandLineArgs = None
        self._iconLocation = None
        self._envTarget = None

        self._ParseLnkFile(self.scPath)

    @property
    def clsid(self):
        return self._clsid

    @property
    def lnkFlags(self):
        return self._lnkFlags

    @property
    def lnkInfoFlags(self):
        return self._lnkInfoFlags

    @property
    def localBasePath(self):
        return self._localBasePath

    @property
    def commonPathSuffix(self):
        return self._commonPathSuffix

    @property
    def commonNetworkRelativeLink(self):
        return self._commonNetworkRelativeLink

    @property
    def name(self):
        return self._name

    @property
    def relativePath(self):
        return self._relativePath

    @property
    def workingDir(self):
        return self._workingDir

    @property
    def commandLineArgs(self):
        return self._commandLineArgs

    @property
    def iconLocation(self):
        return self._iconLocation

    @property
    def envTarget(self):
        return self._envTarget

    @property
    def targetPath(self):
        """
        Args:
            woAnchor (bool): remove the anchor (\\server\path or drive:) from returned path.

        Returns:
            a libpath PureWindowsPath object for combined workingDir/relative path
            or the envTarget

        Raises:
            ShortCutError when no target path found in Shortcut
        """
        target = None
        if self.workingDir:
            target = PureWindowsPath(self.workingDir)
            if self.relativePath:
                target = target / PureWindowsPath(self.relativePath)
            else: target = None

        if not target and self.envTarget:
            target = PureWindowsPath(self.envTarget)

        if not target:
            raise ShortCutError("Unable to retrieve target path from MS Shortcut: shortcut = {}"
                               .format(str(self.scPath)))

        return target

    @property
    def targetPathWOAnchor(self):
        tp = self.targetPath
        return tp.relative_to(tp.anchor)

    def _ParseLnkFile(self, lnkPath):
        with lnkPath.open('rb') as f:
            content = f.read()

            # verify size  (4 bytes)
            hdrSize = struct.unpack('I', content[0x00:0x04])[0]
            if hdrSize != 0x4C:
                raise ShortCutError("MS Shortcut HeaderSize = {}, but required to be = {}: shortcut = {}"
                                   .format(hdrSize, 0x4C, str(lnkPath)))

            # verify LinkCLSID id (16 bytes)
            self._clsid = bytes(struct.unpack('B'*16, content[0x04:0x14]))
            if self._clsid != requiredCLSID:
                raise ShortCutError("MS Shortcut ClassID = {}, but required to be = {}: shortcut = {}"
                                   .format(self._clsid, requiredCLSID, str(lnkPath)))

            # read the LinkFlags structure (4 bytes)
            self._lnkFlags = struct.unpack('I', content[0x14:0x18])[0]
            #logger.debug("lnkFlags=0x%0.8x" % self._lnkFlags)
            position = 0x4C

            # if HasLinkTargetIDList bit, then position to skip the stored IDList structure and header
            if (self._lnkFlags & 0x01):
                idListSize = struct.unpack('H', content[position:position+0x02])[0]
                position += idListSize + 2

            # if HasLinkInfo, then process the linkinfo structure
            if (self._lnkFlags & 0x02):
                (linkInfoSize, linkInfoHdrSize, self._linkInfoFlags,
                 volIdOffset, localBasePathOffset,
                 cmnNetRelativeLinkOffset, cmnPathSuffixOffset) = struct.unpack('IIIIIII', content[position:position+28])

                # check for optional offsets
                localBasePathOffsetUnicode = None
                cmnPathSuffixOffsetUnicode = None
                if linkInfoHdrSize >= 0x24:
                    (localBasePathOffsetUnicode, cmnPathSuffixOffsetUnicode) = struct.unpack('II', content[position+28:position+36])

                #logger.debug("0x%0.8X" % linkInfoSize)
                #logger.debug("0x%0.8X" % linkInfoHdrSize)
                #logger.debug("0x%0.8X" % self._linkInfoFlags)
                #logger.debug("0x%0.8X" % volIdOffset)
                #logger.debug("0x%0.8X" % localBasePathOffset)
                #logger.debug("0x%0.8X" % cmnNetRelativeLinkOffset)
                #logger.debug("0x%0.8X" % cmnPathSuffixOffset)
                #logger.debug("0x%0.8X" % localBasePathOffsetUnicode)
                #logger.debug("0x%0.8X" % cmnPathSuffixOffsetUnicode)

                # if info has a localBasePath
                if (self._linkInfoFlags & 0x01):
                    bpPosition = position + localBasePathOffset

                    # not debugged - don't know if this works or not
                    self._localBasePath = UnpackZ('z', content[bpPosition:])[0].decode('ascii')
                    #logger.debug("localBasePath: {}".format(self._localBasePath))

                    if localBasePathOffsetUnicode:
                        bpPosition = position + localBasePathOffsetUnicode
                        self._localBasePath = UnpackUnicodeZ('z', content[bpPosition:])[0]
                        self._localBasePath = self._localBasePath.decode('utf-16')
                        #logger.debug("localBasePathUnicode: {}".format(self._localBasePath))

                # get common Path Suffix
                cmnSuffixPosition = position + cmnPathSuffixOffset
                self._commonPathSuffix = UnpackZ('z', content[cmnSuffixPosition:])[0].decode('ascii')
                #logger.debug("commonPathSuffix: {}".format(self._commonPathSuffix))
                if cmnPathSuffixOffsetUnicode:
                    cmnSuffixPosition = position + cmnPathSuffixOffsetUnicode
                    self._commonPathSuffix = UnpackUnicodeZ('z', content[cmnSuffixPosition:])[0]
                    self._commonPathSuffix = self._commonPathSuffix.decode('utf-16')
                    #logger.debug("commonPathSuffix: {}".format(self._commonPathSuffix))

                # check for CommonNetworkRelativeLink
                if (self._linkInfoFlags & 0x02):
                    relPosition = position + cmnNetRelativeLinkOffset
                    self._commonNetworkRelativeLink = CommonNetworkRelativeLink(content, relPosition)

                position += linkInfoSize

            # If HasName
            if (self._lnkFlags & 0x04):
                (position, self._name) = self.readStringObj(content, position)
                #logger.debug("name: {}".format(self._name))

            # get relative path string
            if (self._lnkFlags & 0x08):
                (position, self._relativePath) = self.readStringObj(content, position)
                #logger.debug("relPath='{}'".format(self._relativePath))

            # get working dir string
            if (self._lnkFlags & 0x10):
                (position, self._workingDir) = self.readStringObj(content, position)
                #logger.debug("workingDir='{}'".format(self._workingDir))

            # get command line arguments
            if (self._lnkFlags & 0x20):
                (position, self._commandLineArgs) = self.readStringObj(content, position)
                #logger.debug("commandLineArgs='{}'".format(self._commandLineArgs))

            # get icon location
            if (self._lnkFlags & 0x40):
                (position, self._iconLocation) = self.readStringObj(content, position)
                #logger.debug("iconLocation='{}'".format(self._iconLocation))

            # look for environment properties
            if (self._lnkFlags & 0x200):
                while True:
                    size = struct.unpack('I', content[position:position+4])[0]
                    #logger.debug("blksize=%d" % size)
                    if size==0: break

                    signature = struct.unpack('I', content[position+4:position+8])[0]
                    #logger.debug("signature=0x%0.8x" % signature)

                    # EnvironmentVariableDataBlock
                    if signature == 0xA0000001:

                        if (self._lnkFlags & 0x80): # unicode
                            self._envTarget = UnpackUnicodeZ('z', content[position+268:])[0]
                            self._envTarget = self._envTarget.decode('utf-16')
                        else:
                            self._envTarget = UnpackZ('z', content[position+8:])[0].decode('ascii')

                        #logger.debug("envTarget='{}'".format(self._envTarget))

                    position += size

    def readStringObj(self, scContent, position):
        """
        returns:
            tuple: (newPosition, string)
        """
        strg = ''
        size = struct.unpack('H', scContent[position:position+2])[0]
        #logger.debug("workingDirSize={}".format(size))
        if (self._lnkFlags & 0x80): # unicode
            size *= 2
            strg = struct.unpack(str(size)+'s', scContent[position+2:position+2+size])[0]
            strg = strg.decode('utf-16')
        else:
            strg = struct.unpack(str(size)+'s', scContent[position+2:position+2+size])[0].decode('ascii')
        #logger.debug("strg='{}'".format(strg))
        position += size + 2 # 2 bytes to account for CountCharacters field

        return (position, strg)

class CommonNetworkRelativeLink():

    def __init__(self, scContent, linkContentPos):

        self._networkProviderType = None
        self._deviceName = None
        self._netName = None

        (linkSize, flags, netNameOffset,
         devNameOffset, self._networkProviderType) = struct.unpack('IIIII', scContent[linkContentPos:linkContentPos+20])

        #logger.debug("netnameOffset = {}".format(netNameOffset))
        if netNameOffset > 0x014:
            (netNameOffsetUnicode, devNameOffsetUnicode) = struct.unpack('II', scContent[linkContentPos+20:linkContentPos+28])
            #logger.debug("netnameOffsetUnicode = {}".format(netNameOffsetUnicode))
            self._netName = UnpackUnicodeZ('z', scContent[linkContentPos+netNameOffsetUnicode:])[0]
            self._netName = self._netName.decode('utf-16')
            self._deviceName = UnpackUnicodeZ('z', scContent[linkContentPos+devNameOffsetUnicode:])[0]
            self._deviceName = self._deviceName.decode('utf-16')
        else:
            self._netName = UnpackZ('z', scContent[linkContentPos+netNameOffset:])[0].decode('ascii')
            self._deviceName = UnpackZ('z', scContent[linkContentPos+devNameOffset:])[0].decode('ascii')

    @property
    def deviceName(self):
        return self._deviceName

    @property
    def netName(self):
        return self._netName

    @property
    def networkProviderType(self):
        return self._networkProviderType

def UnpackZ (fmt, buf) :
    """
    Unpack Null Terminated String
    """
    #logger.debug(bytes(buf))

    while True :
        pos = fmt.find ('z')
        if pos < 0 :
            break
        z_start = struct.calcsize (fmt[:pos])
        z_len = buf[z_start:].find(b'\0')
        #logger.debug(z_len)
        fmt = '%s%dsx%s' % (fmt[:pos], z_len, fmt[pos+1:])
        #logger.debug("fmt='{}', len={}".format(fmt, z_len))
    fmtlen = struct.calcsize(fmt)
    return struct.unpack (fmt, buf[0:fmtlen])

def UnpackUnicodeZ (fmt, buf) :
    """
    Unpack Null Terminated String
    """
    #logger.debug(bytes(buf))
    while True :
        pos = fmt.find ('z')
        if pos < 0 :
            break
        z_start = struct.calcsize (fmt[:pos])
        # look for null bytes by pairs
        z_len = 0
        for i in range(z_start,len(buf),2):
            if buf[i:i+2] == b'\0\0':
                z_len = i-z_start
                break

        fmt = '%s%dsxx%s' % (fmt[:pos], z_len, fmt[pos+1:])
       # logger.debug("fmt='{}', len={}".format(fmt, z_len))
    fmtlen = struct.calcsize(fmt)
    return struct.unpack (fmt, buf[0:fmtlen])

I hope this helps others as well.
Thanks

A: Create a shortcut using Python (via WSH)
import sys
import win32com.client

shell = win32com.client.Dispatch("WScript.Shell")
shortcut = shell.CreateShortCut("t:\\test.lnk")
shortcut.Targetpath = "t:\\ftemp"
shortcut.save()

Read the Target of a Shortcut using Python (via WSH)
import sys
import win32com.client

shell = win32com.client.Dispatch("WScript.Shell")
shortcut = shell.CreateShortCut("t:\\test.lnk")
print(shortcut.Targetpath)

A: I didn't really like any of the answers available because I didn't want to keep importing more and more libraries and the 'shell' option was spotty on my test machines. I opted for reading the ".lnk" in and then using a regular expression to read out the path. For my purposes, I am looking for pdf files that were recently opened and then reading the content of those files:
# Example file path to the shortcut
shortcut = "shortcutFileName.lnk"

# Open the lnk file using the ISO-8859-1 encoder to avoid errors for special characters
lnkFile = open(shortcut, 'r', encoding = "ISO-8859-1")

# Use a regular expression to parse out the pdf file on C:\
filePath = re.findall("C:.*?pdf", lnkFile.read(), flags=re.DOTALL)

# Close File
lnkFile.close()

# Read the pdf at the lnk Target
pdfFile = open(tmpFilePath[0], 'rb')

Comments:
Obviously this works for pdf but needs to specify other file extensions accordingly.

A: I know this is an older thread but I feel that there isn't much information on the method that uses the link specification as noted in the original question.
My shortcut target implementation could not use the win32com module and after a lot of searching, decided to come up with my own.  Nothing else seemed to accomplish what I needed under my restrictions.  Hopefully this will help other folks in this same situation.
It uses the binary structure Microsoft has provided for MS-SHLLINK.
import struct

path = 'myfile.txt.lnk'
target = ''

with open(path, 'rb') as stream:
    content = stream.read()
    # skip first 20 bytes (HeaderSize and LinkCLSID)
    # read the LinkFlags structure (4 bytes)
    lflags = struct.unpack('I', content[0x14:0x18])[0]
    position = 0x18
    # if the HasLinkTargetIDList bit is set then skip the stored IDList
    # structure and header
    if (lflags & 0x01) == 1:
        position = struct.unpack('H', content[0x4C:0x4E])[0] + 0x4E
    last_pos = position
    position += 0x04
    # get how long the file information is (LinkInfoSize)
    length = struct.unpack('I', content[last_pos:position])[0]
    # skip 12 bytes (LinkInfoHeaderSize, LinkInfoFlags, and VolumeIDOffset)
    position += 0x0C
    # go to the LocalBasePath position
    lbpos = struct.unpack('I', content[position:position+0x04])[0]
    position = last_pos + lbpos
    # read the string at the given position of the determined length
    size= (length + last_pos) - position - 0x02
    temp = struct.unpack('c' * size, content[position:position+size])
    target = ''.join([chr(ord(a)) for a in temp])

A: Alternatively, you could try using SHGetFolderPath().  The following code might work, but I'm not on a Windows machine right now so I can't test it.
import ctypes

shell32 = ctypes.windll.shell32

# allocate MAX_PATH bytes in buffer
video_folder_path = ctypes.create_string_buffer(260)

# 0xE is CSIDL_MYVIDEO
# 0 is SHGFP_TYPE_CURRENT
# If you want a Unicode path, use SHGetFolderPathW instead
if shell32.SHGetFolderPathA(None, 0xE, None, 0, video_folder_path) >= 0:
    # success, video_folder_path now contains the correct path
else:
    # error

A: Basically call the Windows API directly. Here is a good example found after Googling:
import os, sys
import pythoncom
from win32com.shell import shell, shellcon

shortcut = pythoncom.CoCreateInstance (
  shell.CLSID_ShellLink,
  None,
  pythoncom.CLSCTX_INPROC_SERVER,
  shell.IID_IShellLink
)
desktop_path = shell.SHGetFolderPath (0, shellcon.CSIDL_DESKTOP, 0, 0)
shortcut_path = os.path.join (desktop_path, "python.lnk")
persist_file = shortcut.QueryInterface (pythoncom.IID_IPersistFile)
persist_file.Load (shortcut_path)

shortcut.SetDescription ("Updated Python %s" % sys.version)
mydocs_path = shell.SHGetFolderPath (0, shellcon.CSIDL_PERSONAL, 0, 0)
shortcut.SetWorkingDirectory (mydocs_path)

persist_file.Save (shortcut_path, 0)

This is from http://timgolden.me.uk/python/win32_how_do_i/create-a-shortcut.html.
You can search for "python ishelllink" for other examples.
Also, the API reference helps too: http://msdn.microsoft.com/en-us/library/bb774950(VS.85).aspx

A: It's easy as opening ".exe" file. Here also, we are going to use the os module for this. You just have to create a shortcut .lnk and store it in any folder of your choice. Then, in any Python file, first import the os module (already installed, just import). Then, use a variable, say path, and assign it a string value containing the location of your .lnk file. Just create a shortcut of your desired application. At last, we will use os.startfile()
to open our shortcut.
Points to remember:

*

*The location should be within double inverted commas.

*Most important, open Properties. Then, under that, open "Details". There, you can get the exact name of your shortcut. Please write that name with ".lnk" at last.

Now, you have completed the procedure. I hope it helps you. For additional assistance, I am  leaving my code for this at the bottom.
import os

path = "C:\\Users\\hello\\OneDrive\\Desktop\\Shortcuts\\OneNote for Windows 10.lnk"

os.startfile(path)

In my code, I used path as variable and I had created a shortcut for OneNote. In path, I defined the location of OneNote's shortcut. So when I use os.startfile(path), the os module is going to open my shortcut file defined in variable path.

A: this job is possible without any modules, doing this will return a b string having the destination of the shortcut file. Basically what you do is you open the file in read binary mode (rb mode). This is the code to accomplish this task:
with open('programs.lnk - Copy','rb') as f:
    destination=f.read()

i am currently using python 3.9.2, in case you face problems with this, just tell me and i will try to fix it.

A: A more stable solution in python, using powershell to read the target path from the .lnk file.

*

*using only standard libraries avoids introducing extra dependencies such as win32com

*this approach works with the .lnks that failed with jared's answer, more details

*we avoid directly reading the file, which felt hacky, and sometimes failed

import subprocess

def get_target(link_path) -> (str, str):
    """
    Get the target & args of a Windows shortcut (.lnk)
    :param link_path: The Path or string-path to the shortcut, e.g. "C:\\Users\\Public\\Desktop\\My Shortcut.lnk"
    :return: A tuple of the target and arguments, e.g. ("C:\\Program Files\\My Program.exe", "--my-arg")
    """
    # get_target implementation by hannes, https://gist.github.com/Winand/997ed38269e899eb561991a0c663fa49
    ps_command = \
        "$WSShell = New-Object -ComObject Wscript.Shell;" \
        "$Shortcut = $WSShell.CreateShortcut(\"" + str(link_path) + "\"); " \
        "Write-Host $Shortcut.TargetPath ';' $shortcut.Arguments "
    output = subprocess.run(["powershell.exe", ps_command], capture_output=True)
    raw = output.stdout.decode('utf-8')
    launch_path, args = [x.strip() for x in raw.split(';', 1)]
    return launch_path, args

# to test
shortcut_file = r"C:\Users\REPLACE_WITH_USERNAME\AppData\Roaming\Microsoft\Windows\Start Menu\Programs\Accessibility\Narrator.lnk"
a, args = get_target(shortcut_file)
print(a)  # C:\WINDOWS\system32\narrator.exe

(you can remove -> typehinting to get it to work in older python versions)
I did notice this is slow when running on lots of shortcuts. You could use jareds method, check if the result is None, and if so, run this code to get the target path.

A: The nice approach with direct regex-based parsing (proposed in the answer) didn't work reliable for all shortcuts in my case. Some of them have only relative path like ..\\..\\..\\..\\..\\..\\Program Files\\ImageGlass\\ImageGlass.exe (produced by msi-installer), and it is stored with wide chars, which are tricky to handle in Python.
So I've discovered a Python module LnkParse3, which is easy to use and meets my needs.
Here is a sample script to show target of a lnk-file passed as first argument:
import LnkParse3
import sys

with open(sys.argv[1], 'rb') as indata:
    lnk = LnkParse3.lnk_file(indata)
    print(lnk.lnk_command)

A: I arrived at this thread looking for a way to parse a ".lnk" file and get the target file name.
I found another very simple solution:
pip install comtypes

Then
from comtypes.client import CreateObject
from comtypes.persist import IPersistFile
from comtypes.shelllink import ShellLink

# MAKE SURE THIS VAT CONTAINS A STRING AND NOT AN OBJECT OF 'PATH'
# I spent too much time figuring out the problem with .load(..) function ahead
pathStr="c:\folder\yourlink.lnk"

s = CreateObject(ShellLink)
p = s.QueryInterface(IPersistFile)
p.Load(pathStr, False)
print(s.GetPath())
print(s.GetArguments())
print(s.GetWorkingDirectory())
print(s.GetIconLocation())
try:
    # the GetDescription create exception in some of the links
    print(s.GetDescription())
except Exception as e:
    print(e)
print(s.Hotkey)
print(s.ShowCmd)

Based on this great answer...
https://stackoverflow.com/a/43856809/2992810

redpajama_set_name: RedPajamaStackExchange


text:
Q: how can i create rows in 2 models(tables) with reusable functions based on one form I want to save data in two models from a single POST request. Two different models (OF, Encours)

Here's my models.py:

class OF(models.Model):
Id_OF= models.BigAutoField(primary_key=True)
Numero_Of = models.BigIntegerField(unique=True,blank=False)
class Dimension_OF(models.TextChoices):
    PD_inférieur_à_500mm="PD"
    MD_Entre_500_et_1500mm="MD"
    GD_supérieur_à_1500mm="GD"
Dimension_OF = models.CharField(max_length=20, blank=False,choices=Dimension_OF.choices)
class Machine(models.TextChoices):
    MGP1="MGP1"
    MGP2="MGP2 "
    MGP3="MGP3"
    MGP4="MGP4"
    MGP5="MGP5"
    MGP6="MGP6"
    MGP7="MGP7"
    MGP8="MGP8"
Machine=models.CharField(max_length=10,choices=Machine.choices, blank=False)
class Scenario(models.TextChoices):
    Ajustage_Controle="scenario1"
    Ajustage_Redressage_Controle="scenario2"
    Ajustage_Formage_Controle="scenario3"
    Ajustage_Redressage_Formage_Controle="scenario4"

Scenario = models.CharField(max_length=50,choices=Scenario.choices, blank=False)
Date_E_initial=models.DateTimeField(auto_now_add=True,auto_now=False)
Date_S_Final=models.DateTimeField(null=True, blank=True)
Etat_OF=models.CharField(max_length=50, null=True, blank=True)
Nb_jrs_att_Usin=models.DurationField(null=True, blank=True)
Nb_jrs_att_TM=models.DurationField(null=True, blank=True)
Nb_jrs_att_total=models.DurationField(null=True, blank=True)

def _str_(self):
    return self.Scenario

class Encours(models.Model):
Id_encours=models.IntegerField(primary_key=True)
OF = models.ForeignKey(OF, on_delete=models.CASCADE )
class Nom_encours(models.TextChoices):
    EN_MGP1="Encours MGP1"
    EN_MGP2="Encours MGP2"
    EN_MGP3="Encours MGP3"
    EN_MGP4="Encours MGP4"
    EN_MGP5="Encours MGP5"
    EN_MGP6="Encours MGP6"
    EN_MGP7="Encours MGP7"
    EN_MGP8="Encours MGP8"
    EN_AJU_GD="Encours Ajustage GD"
    EN_AJU_MD="Encours Ajustage MD"
    EN_AJU_PD="Encours Ajustage PD"
    EN_RED="Encours Redressage"
    EN_For="Encours Formage"
    EN_Contr_GD="Encours Contrôle GD"
    EN_Contr_MD="Encours Contrôle MD"
    EN_Contr_PD="Encours Contrôle PD"
Nom_encours = models.CharField(max_length=30,choices=Nom_encours.choices)
Capacite = models.IntegerField(default=0)
Date_E_Encours=models.DateTimeField(null=True, blank=True)
Date_S_Encours=models.DateTimeField(null=True, blank=True)
def _str_(self):
    return self.Nom_encours

But before saving data into Encours I want to define some functions to test field
for exemple ; if OF.Machine=='MGP1' then create a row in Encours model with Nom_Encours='Encours MGP1' and Date_E_Encours = Date_E_initial that automatically added.

views.py

def lancerOF(request):

form = OFLancementForm(request.POST or None)
if request.method == 'POST':
    if form.is_valid():
        form.save()
        messages.success(request, 'OF lancé avec succès', extra_tags='alert')
        return redirect('lancer')
    else:
        messages.warning(request, 'Verifiez les données saisies')

return render(request, "lancerOF.html",{'form':form})

and i use a simple form

class OFLancementForm(forms.ModelForm):
class Meta:
    model = OF
    fields = {
       'Numero_Of',
       'Dimension_OF',
       'Machine',
       'Scenario'
    }
    widgets = { "Dimension_OF": forms.RadioSelect ,"Machine": forms.RadioSelect ,"Scenario": forms.RadioSelect}

if this is possible, where can i do test to check OF attributes and save data into my models.
PS: this is my first real project with django.
Can anyone help me please?

A: def lancerOF(request):

    form = OFLancementForm(request.POST or None)
    if request.method == 'POST':
        if form.is_valid():
            myobject = form.save()
            # here you can do your logic
            if myobject.Machine == "MPG1":
                ...
            messages.success(request, 'OF lancé avec succès', extra_tags='alert')
            return redirect('lancer')
        else:
            messages.warning(request, 'Verifiez les données saisies')

    return render(request, "lancerOF.html",{'form':form})

Or another method is using Django's post_save signal.
Or you can override OF's save() method:
class OF(models.Model):
    def save(self, *args, **kwargs):
        super(OF, self).save(*args, **kwargs)
        if self.Machine == "MPG1":
            # your logic here.


text:
Q: I was deploying my python ML project on Heroku, got these errors while I was developing in the Build main section got these errors
Collecting importlib==1.0.4
         Downloading importlib-1.0.4.zip (7.1 kB)
         Preparing metadata (setup.py): started
         Preparing metadata (setup.py): finished with status 'error'
         error: subprocess-exited-with-error

         × python setup.py egg_info did not run successfully.
         │ exit code: 1
         ╰─> [1 lines of output]
             ERROR: Can not execute `setup.py` since setuptools is not available in the build environment.
             [end of output]

         note: This error originates from a subprocess, and is likely not a problem with pip.
       error: metadata-generation-failed

       × Encountered error while generating package metadata.
       ╰─> See above for output.

       note: This is an issue with the package mentioned above, not pip.
       hint: See above for details.
 !     Push rejected, failed to compile Python app.
 !     Push failed

A: I can see in the error this line: ERROR: Can not execute setup.py since setuptools is not available in the build environment which means you haven't added the setuptools module to the build environment of the project. Try to use pip install setuptools to install the module.


text:
Q: Process Javascript Array of Arrays with Recursion I'm making a real-time chat app that allows you to reply to other people. The data is stored where each new message has an array to store replies to it, so an array may look like
FIRST MESSAGE
---REPLY TO FIRST MESSAGE
   ---REPLY TO SUB MESSAGE
---REPLY TO FIRST MESSAGE
   ---REPLY TO SUB MESSAGE
   ---REPLY TO SUB MESSAGE

I'm currently using the following code:
function process (obj, func) {
    func(obj);
    if (obj.child) {
        obj.child.forEach(function (child) {
            process(child, func);
        });
    }
}

And I call it with (data is the array of all messages):
for (i = 0; i < data.length; i++) {
            process(data[i]['replies'], function (obj) {
            });
}

This only seems to get the first reply to each message, and just skips the rest. Any ideas for a recursive function that would prevent that? I'm really stuck here. Thanks for any help!

A: Nevermind! I got it. I needed to call another loop inside of the process function, like:
for (i = 0; i < data.length; i++) {
    process(data[i]['replies'], function (obj) {
        for (c = 0; c < obj.length; c++) {
        }
    });
}


text:
Q: javascript changing the style

    655 3338
    10-May-2013

    655 3338
    10-May-2013

Good day to all, im a newbie in terms of coding in the language of javascript, im developing a simple hide show, a code above(piece of code) is a table when u click the table cell 10-May-2013 some how a table row below will show, and in that event, im correct? What is missing im my code is when i click again the table cell 10-May-2013 it will hide again, or back to its default style(hide or collapse for table).

A: Try
function hide(){
    if(document.getElementById("xxx").style.visibility != 'visible'){
        document.getElementById("xxx").style.visibility='visible';
    } else {
        document.getElementById("xxx").style.visibility='collapse';
    }
}

Demo: Fiddle

A: You may be better to toggle the row's display property to "none" and "" (empty string) as display is widely supported and seems better suited here.
e.g.

<button onclick="hideNextRow(this);">Show/Hide next row</button>

The next row


text:
Q: Modifying EHCache beans defined in Spring Assuming the belowcache definition in Spring, is it possible to set bootstrapCacheLoaderFactory and cacheEventListenerFactory through a separate ehcache.xml file or in the same xml file? If we set them in the Cache definitions in ehcache.xml, which cache definitions(in the current xml file or ehcache.xml ?!) will be applied?
Where can I set cacheManagerPeerProviderFactory and cacheManagerPeerListenerFactory for CacheManager?
    <bean id="reportCache" class="org.springframework.cache.ehcache.EhCacheFactoryBean">
        <property name="cacheManager" ref="cacheManager"/>
        <property name="maxElementsInMemory" value="${cache.report.maxMemoryElements}"/>
      </bean>

<bean id="cacheManager" class="org.springframework.cache.ehcache.EhCacheManagerFactoryBean">
  <property name="configLocation" value="WEB-INF/ehcache.xml"/>

  </bean>

Would the below tag in ehcache.xml work?
 <cache name="reporteCache">
    <bootstrapCacheLoaderFactory class = "net.sf.ehcache.distribution.RMIBootstrapCacheLoaderFactory" properties = "bootstrapAsynchronously=false, maximumChunkSizeBytes=5000000"/>

            <cacheEventListenerFactory class = "net.sf.ehcache.distribution.RMICacheReplicatorFactory" properties="replicateAsynchronously=true, asynchronousReplicationIntervalMillis=100"/>

       </cache>

Both of the xml and java code would be fine.
Thank you in advance.

A: Just in case someone else is reading this? You can set the cacheManagerPeerListenerFactory in your ehcache.xml file as follows
<cacheManagerPeerProviderFactory
        class="net.sf.ehcache.distribution.RMICacheManagerPeerProviderFactory"
        properties="peerDiscovery=automatic, multicastGroupAddress=230.0.0.2,
                multicastGroupPort=4455, timeToLive=1"/>
<cacheManagerPeerListenerFactory
        class="net.sf.ehcache.distribution.RMICacheManagerPeerListenerFactory"
        properties="host=hostname,port=40001, socketTimeoutMillis=2000"/>


text:
Q: Android: NullPointerExceptions when recall function with Thread I'm having a problem with this.
I'm using canvas to draw character.
@Override
public void onDraw(Canvas canvas) {
    this.mcanvas = canvas;
    mcanvas.drawBitmap(mBg, null, mRect, mPaint);

    for (int i = temps.size() - 1; i >= 0; i--) {
        temps.get(i).onDraw(mcanvas);
    }
    for (Sprite sprite : sprites) {
        sprite.onDraw(canvas);
    }
    while(timeleft>0) {
        timeleft=(int) (timeleft-1);
        score.onDraw(canvas,timeleft); break;
    }
}

when i set drawBitmap for this function and Thread class run this.
@Override
public void run() {
    long ticksPS = 1000 / FPS;
    long startTime;
    long sleepTime;
    while (running) {
        Canvas c = null;
        startTime = System.currentTimeMillis();
        try {
            c = view.getHolder().lockCanvas();
            synchronized (view.getHolder()) {
                view.onDraw(c);
            }

        } finally {
            if (c != null) {
                view.getHolder().unlockCanvasAndPost(c);
            }
        }
        sleepTime = ticksPS - (System.currentTimeMillis() - startTime);
        try {
            if (sleepTime > 0)
                sleep(sleepTime);
            else
                sleep(2);
        } catch (Exception e) {
        }

    }

}

But when I replay game, logcat show error and close app.
06-13 02:04:12.347: E/AndroidRuntime(956): FATAL EXCEPTION: Thread-94
06-13 02:04:12.347: E/AndroidRuntime(956): java.lang.NullPointerException
06-13 02:04:12.347: E/AndroidRuntime(956):  at com.example.Boss.GameView.onDraw(GameView.java:353)
06-13 02:04:12.347: E/AndroidRuntime(956):  at com.example.Boss.GameLoopThread.run(GameLoopThread.java:30)

it shows an error in:
mcanvas.drawBitmap(mBg, null, mRect, mPaint);

and
view.onDraw(c);

I don't know what happened with it. i need help. Thanks in advance!.

A:  for (Sprite sprite : sprites) {
    sprite.onDraw(canvas);
    }

try using for-loop instead, I used to have crash when running foreach loops 2 or more times in game, also post more details:
 for(int i =0; i< sprites.size(); i++){
      Sprite s = sprites.get(i);
      s.onDraw(canvas);
   }

A: The error seems to be that mcanvas is null. This can happen when lockCanvas() returns null. Please check the documentation of SurfcaeHolder.lockCanvas() which says:

A null is returned if the surface has not been created or otherwise cannot be edited. You will usually need to implement Callback.surfaceCreated to find out when the Surface is available for use.


text:
Q: How to develop Extjs component like date Picker? I'm ExtJs 6.0 framework developer.
I want to develop a component like date that when user click it, It open a window and this window have some textfields and other Extjs components. My problem is when I want to use this component as a grid cell editor. it does not show the component. In other words, I want to develop a custom picker.
How do I do?

A: You can extend Ext.form.field.Picker and implement createPicker:

An abstract class for fields that have a single trigger which opens a
  "picker" popup below the field, e.g. a combobox menu list or a date
  picker. It provides a base implementation for toggling the picker's
  visibility when the trigger is clicked, as well as keyboard navigation
  and some basic events. Sizing and alignment of the picker can be
  controlled via the matchFieldWidth and pickerAlign/pickerOffset config
  properties respectively.
You would not normally use this class directly, but instead use it as
  the parent class for a specific picker field implementation.
  Subclasses must implement the createPicker method to create a picker
  component appropriate for the field.

It can look like:
Ext.define('Fiddle.view.FooPicker', {

    extend: 'Ext.form.field.Picker',

    xtype: 'foo-picker',

    createPicker: function(){

        return Ext.widget('container',{
            padding: 20,
            floating: true,
            items: [
                {
                    xtype: 'textfield'
                },
                {
                    xtype: 'box',
                    html: 'Foo'
                }
            ]
        })

    }

});

https://fiddle.sencha.com/#fiddle/1139


text:
Q: Check if mySql is installed on server Is there a way to determine if mySql has been installed on a Linux server?

A: What version of linux?
Debian
dpkg -l 'mysql*'

A: Assuming that you are looking for a mysql binary installed with a typical package, run the command:
mysql

or
mysql --version

If it comes back with a response, it is installed, if it says "command not found" then it is not installed.

A: How about rpm -q mysql (Fedora/RedHat)

A: Other than the good suggestions above, try:
locate mysqld_safe

or
ls /etc/init.d | grep mysql

If you think it might be running already try:
ps waxu | grep mysql

or
netstat -pan | grep mysql

A: On every distribution that I know of, MySQL installs some shared libraries for its client, named appropriately limbysqlclient. You can check for this by using the ldconfig tool, which will query to see if the object is installed:
ldconfig -p | grep mysqlclient
        libmysqlclient_r.so.15 (libc6) => /usr/lib/libmysqlclient_r.so.15
        libmysqlclient_r.so.14 (libc6) => /usr/lib/libmysqlclient_r.so.14
        libmysqlclient_r.so.12 (libc6) => /usr/lib/libmysqlclient_r.so.12
        libmysqlclient_r.so.10 (libc6) => /usr/lib/libmysqlclient_r.so.10
        libmysqlclient_r.so (libc6) => /usr/lib/libmysqlclient_r.so
        libmysqlclient.so.15 (libc6) => /usr/lib/libmysqlclient.so.15
        libmysqlclient.so.14 (libc6) => /usr/lib/libmysqlclient.so.14
        libmysqlclient.so.12 (libc6) => /usr/lib/libmysqlclient.so.12
        libmysqlclient.so.10 (libc6) => /usr/lib/libmysqlclient.so.10
        libmysqlclient.so (libc6) => /usr/lib/libmysqlclient.so

This tells you that there's a very good chance that MySQL is installed. Its very rare that someone would install the shared objects only, without installing at least the client. Now, check for the existence of the actual client and server:
root@tower:~ # which mysqld_safe
/usr/bin/mysqld_safe
root@tower:~ # which mysql
/usr/bin/mysql
root@tower:~ #

The `which' program may not be installed, so check for it via:
root@tower:~ # which which
/usr/bin/which

Hope this helps. Short of querying the package manager (kind of hard to do in a script if you have many systems running different distributions) it seems a very reliable way to tell.

A: The easiest and most distro-agnostic way of answering your question is;
find / -name mysql


text:
Q: How to get
* items from HTML with their Index into a JavaScript Array? I made a reorder list using Sortable jQuery. After the reorder, I want to get the new Order of LI Items. How can I achieve this?

Item 2

Item 3

Item 4

Item 5

A: This will give you an array of objects containing the ID and index of each li:
var order = $('li').map(function(i) {
    return { id: this.id, index: i };
}).get();

Example - http://jsfiddle.net/czprf/

A: Selecting them with jQuery will get them in their new order:
var myLis = $('.ui-state-default');

myLis.eq(0).html(); // This will return Item 2
myLis.eq(1).html(); // This will return Item 3
myLis.eq(2).html(); // This will return Item 4
myLis.eq(3).html(); // This will return Item 5

jQuery always selects the elements closest to the top of the DOM first.

A: try like this:

Item 2

Item 3

Item 4

Js:
var nodeList = Array.prototype.slice.call( document.getElementById('AAA').children ),
      liRef = document.getElementsByClassName('match')[0];
console.log( nodeList.indexOf( liRef ) );

A: What you want is to access the stop event of the sortable plugin.
var order;
$('#sortable').sortable({
    stop: function(){
        order = $('#sortable li').map(function(i, li){
            return {index: i, id: li.id, text: li.innerHTML};
        });
        console.log(order);
    }
});

Here's your jsFiddle;


text:
Q: trace incoming call generates error in blackberry in my application i try to trace an incoming call using AbstractPhoneListener.
The call gets traced but the problem is that it generates an error and i have to exit the simulator
I tested on device but when a call arrives nothing happens as i have tried to do!!!!
ERROR = "Access violation reading from 0x00000004"
code:
public class CallTrace extends AbstractPhoneListener
{

    CallTrace()
    {

    }

    public void callIncoming(int callId)
    {
        PhoneCall call = Phone.getCall(callId);
        String callNumber = call.getDisplayPhoneNumber();l

        System.out.println("call traced!!!!!!!!");

    }

}

code:
public class BackgroundListener extends Thread
{
    private static PersistentObject timeStore,NPZstore;
    private static Vector timeVector,mode;
    static CallTrace calltrace;
    String[] time1,time2;
    int time1Flag=0,time2Flag=0;

     public BackgroundListener()
     {
         calltrace = new CallTrace();
     Phone.addPhoneListener(calltrace);
         this.start();
     }
     boolean stopThread = false;

     public void run()
     {
          while (!stopThread)
          {
        //do some coding here like matching of dates etc.that works well
               try
               {
                   sleep(6000) ;
               }
               catch (Exception e)
               {
                    System.out.println("exception in background thread:"+e);
               }
          }
     }

     public synchronized void stop()
     {
          stopThread = true;
     }
     protected void onExit()
     {
          this.stop();
     }
  }

code:
public class HomeScreen extends UiApplication implements GlobalEventListener
{
    private static PersistentObject NPZstore;
    private static Vector mode;
    static boolean modeValue=false;
    static BackgroundListener obj;

    public static void main(String[] args)
    {
        if(args!=null && args[0].equals("gui"))
        {
            HomeScreen homescreen = new HomeScreen();
            homescreen.enterEventDispatcher();
        }
        else
        {
          obj = new BackgroundListener();
        }
    }
    HomeScreen()
    {
        pushScreen(new WorkScreen());
    }

public void eventOccurred(long guid, int data0, int data1, Object object0,
  Object object1)
        {

    }
}
class WorkScreen extends MainScreen
{
    CustomButtonField REDbutton,GREENbutton;
    HorizontalFieldManager hfmRED,hfmGREEN;
    private static PersistentObject NPZstore;
    private static Vector mode;
    boolean modeValue=false;
    static CallTrace calltrace;
    PopupScreen selectBluetoothType;
    final Bitmap background2;

    public WorkScreen()
    {
    //adding some fields here
        }
}

A: This looks like a Windows error caused by the simulator crashing.  So it's not a bug in your code but probably a bug in the simulator.  I'd suggest downloading and installing a different simulator - even if it's the same model pick the latest build.  The simulators that ship with the JDE are usually quite dated.


text:
Q: Problem finding zeros of complex polynomial I'm trying to solve this problem
$$ z^2 + (\sqrt{3} + i)|z| \bar{z}^2 = 0 $$
So, I know $ |z^2| = |z|^2 = a^2 + b ^2 $ and $ \operatorname{Arg}(z^2) = 2 \operatorname{Arg} (z) - 2k \pi = 2 \arctan (\frac{b}{a} ) - 2 k\pi $ for a $ k \in \mathbb{Z} $.  Regarding the other term, I know $ |(\sqrt{3} + i)|z| \bar{z}^2 | = |z|^3 |\sqrt{3} + i| = 2 |z|^3 = 2(a^2 + b^2)^{3/2} $ and because of de Moivre's theorem, I have $ \operatorname{Arg} [(\sqrt{3} + i ) |z|\bar{z}^2] = \frac{\pi}{6} + 2 \operatorname{Arg} (z) - 2Q\pi $.
Using all of this I can rewrite the equation as follows
$$\begin{align*}
&|z|^2 \Bigl[ \cos (2 \operatorname{Arg} (z) - 2k \pi) + i \sin (2 \operatorname{Arg}(z) - 2k \pi)\Bigr]\\
&\qquad \mathop{+} 2|z|^3 \Biggl[\cos \left(\frac{\pi}{6} + 2 \operatorname{Arg} (z) -2Q\pi\right) + i \sin \left(\frac{\pi}{6} + 2 \operatorname{Arg} (z) -2Q\pi\right)\Biggr] = 0
\end{align*} $$
Which, assuming $ z \neq 0 $, can be simplified as
$$\begin{align*}
&\cos (2 \operatorname{Arg} (z) - 2k \pi) + i \sin (2 \operatorname{Arg} (z) - 2k \pi) \\
&\qquad\mathop{+} 2 |z|\Biggl[\cos \left(\frac{\pi}{6} + 2 \operatorname{Arg} (z) -2Q \pi \right) + i \sin \left(\frac{\pi}{6} + 2 \operatorname{Arg} (z) -2Q\pi\right)\Biggr] = 0
\end{align*} $$
Now, from this I'm not sure how to go on. I tried a few things that got me nowhere like trying to solve
$$ \cos (2 \operatorname{Arg}(z) - 2k \pi) = 2 |z| \cos \left(\frac{\pi}{6} + 2 \operatorname{Arg} (z) -2Q\pi\right) $$
I'm really lost here, I don't know how to keep going and I've looked for error but can't find them. Any help would be greatly appreciated.

A: Here is an alternative to solving it using polar form.
Let $z=a+bi$, so that $\bar{z}=a-bi$ and $|z|=\sqrt{a^2+b^2}$. Then you want to solve
$$(a+bi)^2+(\sqrt{3}+i)\sqrt{a^2+b^2}(a-bi)^2=0,$$
which expands to
$$(a^2-b^2)+2abi+(\sqrt{3}+i)\sqrt{a^2+b^2}\left((a^2-b^2)-2abi\right)=0$$
Thus, we need both the real part and the imaginary part of the left side to be 0, i.e.
$$(a^2-b^2)+\sqrt{a^2+b^2}\left(\sqrt{3}\cdot (a^2-b^2)+2ab\right)=0$$
and
$$2ab+\sqrt{a^2+b^2}\left(-2ab\sqrt{3}+(a^2-b^2)\right)=0.$$
It should be possible to solve these equations by simple manipulations, though I haven't worked it out myself yet.

A: The relation is equivalent to $z^2=-(\sqrt{3}+i)|z|\overline{z}^2$. $z=0$ is a solution, so in the following $z \neq 0$. Take modulus of both sides and denote $r=|z|=|\overline{z}|$. Then $r^2=2r^3$, which means $r=\frac{1}{2}$.
The relations turns to $z^2+\frac{1}{2}(\sqrt{3}+i)\overline{z}^2=0$. Multiply by $z^2$ and get $z^4+\frac{1}{2}(\sqrt{3}+i)\frac{1}{16}=0$. Write it in trigonometric form
$$ z^4=\frac{1}{16}\left(-\frac{\sqrt{3}}{2}-i\frac{1}{2}\right)=\frac{1}{16}(\cos \frac{7\pi}{6}+\sin \frac{7\pi}{6})$$.
From here on it is just the extraction of complex roots.
[edit] I did not answer your question, as to how to continue your calculations, but I can say from experience that in most complex numbers problems the substitution $z=a+bi$ gets you in more troubles in the end, than working with the properties of complex conjugate, modulus and trigonometric form. You can see that in my solution no great computational problems were encountered.


text:
Q: Swift Pass/Save Text From TextView Inside CustomCell & Make The Text Not Disappear After Cell Resuse I struggle a bit to find or think of a way that I can store the textView text.
so later I can pass it back to the server if needed.
I have a TextView Inside a CustomCell UITableViewCell. (I have 2 sections inside my tableview and in each section there is that custom cell with a textView inside.)
I need to somehow pass or save the text that the user have written so I could pull that text and send it somewhere else.. and each time the text inside my "reusable" cell gets reused the text disappears.
I have tried to save it inside my customCell Swift but I don't think that's a good idea to save the text inside a customCell file.
any one have idea?
thank you!

A: While implementing tableView, we should make sure to have some data source that is data driven. What I mean here is to create a model that drives your tableView's numberOfSections, numberOfRowsInSection etc. This way you can have a property in your model to store textView's text.
Sample Model:
    struct TableViewModel {
    // this will handle number of sections
    var sections: [TableViewSectionModel]
}

struct TableViewSectionModel {
    // this will handle number of rows
    var rows: [TableViewRowModel]
}

struct TableViewRowModel {
    var textViewText: String
    /*
     Other properties to fill in
     */
}

Using this you can create your dataModel like this:
var cell1 = TableViewRowModel(textViewText: "")
var cell2 = TableViewRowModel(textViewText: "")

var section1 = TableViewSectionModel(rows: [cell1, cell2])
var section2 = TableViewSectionModel(rows: [cell1, cell2])

var data = TableViewModel(sections: [section1, section2])

This will help to update property in model and you can have your data to pass it to backend later.

A: First step:
Create a model to populate the cells.
struct myModel {
let textFromCustomCell: string = ""
}

Create a list of models (to populate the tableview)
Second step:
This has several way to do so but i chose the delegate approach.

*

*Make your CustomCell conform to UITextViewDelegate.

*Save a indexPath var on the CustomCell:
var indexPath: IndexPath?

*Implement this UITextview Delegate method on the cell:
func textViewDidChange(textView: UITextView)

*Set the textView delegate in the cell awakeFromNib:
 override func awakeFromNib() {
super.awakeFromNib()
textField.delegate = self

}
5.Create a CustomCellDelegate:
protocol CustomCellDelegate: AnyObject {
    func cellTextDidChanges(indexPath: IndexPath, text: String)
}

*Call this function on the cell when needed (probably inside textViewDidChange function implementation on the cell).

*Make the viewControlller that holds the tableview to conform to your CustomCellDelegate

*Implement the CustomCellDelegate cellTextDidChanges method on your viewControlller

*On the cellTextDidChanges implementation you should update the correct model text on the model list you created according to the indexPath.
Remember when the tableview will be populated for the first time the text will be empty.


text:
Q: How to convert raster dtype from uint8 to float32? I want to make stack of multiple rasters but some of them have float32 and some of them have uint8 as dtype. which giving me this error :
ValueError: the array's dtype 'uint8' does not match the file's dtype 'float32'
My used code:
import os
import earthpy.spatial as es
from earthpy.io import path_to_example
band_fnames = ["red.tif", "green.tif", "blue.tif"]
band_paths = [path_to_example(fname) for fname in band_fnames]
destfile = "./stack_result.tif"
arr, arr_meta = es.stack(band_paths, destfile)

Anybody has idea how to solve this?

A: You can use the astype method of numpy arrays:
import numpy as np

a = np.array([1, 2], dtype=np.unit8)
a.dtype
>>> dtype('uint8')

b = a.astype(np.float32)
b.dtype
>>> dtype('float32')

# values are the same but now floats
b
>>> array([1., 2.], dtype=float32)

I would suggest converting all the arrays you want to stack to be the same dtype using something like this above.


text:
Q: Message passing using akka with case class ActorA(processB:ActorRef) extends Actor with ActorLogging{
  def receive = {
    case (0) =>
       println(1000)
    case (_) =>
       println (2*_)
   }
}

I am writing this code to output 1000 if message passed is 0 and 2x otherwise but it is telling me that * is not a member of Any and missing parameter type for expanded function

A: The messages to actors can be of any type so your final pattern is against a value of type Any.
If you want to only handle Int you need to specify the type in the pattern.
Additionally you can't match against _ and then use _ as if it's a variable.  They mean different things.  The first one in the case means that you don't care what the value is.
The second one is a placeholder for a function parameter.
What you want is:
class ActorA(processB:ActorRef) extends Actor with ActorLogging{
   def receive = {
      case (0) =>
         println(1000)
      case x:Int =>
         println (2*x)
   }
}

A: You could add this case to the receive function:
case (number:Int) => println (2*number)

Remember, that when you use the underscore _ in the case, you cannot use the variables value after the => sign.


text:
Q: Best way to do a dictionary search I've written a dynamic programming algorithm to solve a vehicle routing problem with time windows.  The goal is to find the cheapest way to assign locations to vehicles so that the vehicle arrives at each location inside a given time window.  I store the partial solutions that I generate in a dictionary with the format:

{(set{locations visited}, tuple(current locations), tuple(current time), version):(tuple(costs), tuple(previous location), tuple(previous time), tuple(vehicle order), previous version)}

I was excited because the program seems to function correctly, but it's very slow.  When running the code on relatively small test cases (15 randomly generated locations) it's taking 280,000+ seconds.  As part of my code I include several functions to eliminate partial solutions that cannot be part of a feasible solution.  Two of these functions need to use a dictionary search to identify the fastest (or cheapest) way to visit a certain set of locations and end at certain locations.  To do this I use the dictionary search:
self.label_check = {k: v for k, v in self.memo.items() if k[0]==self.new_visited and k[1]==self.sorted_nlp}

I have a feeling this is my biggest time expenditure as the dictionary (memo) is 650,000+ items by the end of the program.
I was wondering, would I be better off creating a list of dictionaries based on the size of the set of locations visited?  When I do those dictionary searches the specific locations will change, but the number of locations will not.  For example if I'm considering adding the label {{1,2,3}, (1,2), (10,5), 1}.  I would want to search for any dictionaries keys with key[0] = {1,2,3} and key[1] = (1,2).  So I'd only need to search the dictionary keys where the locations visited have size 3.
My question is will this change create a significant time savings?


text:
Q: Fullcalendar V4 reload events. removeEventSource doesn't exist I'm trying to add a calendar on my site but I don't know how could be possible to reload events from an ajax source. On previous versions you can remove the event source, add the nwe one and redraw the calendar, but in this version, I read in the documentation that it only have the addEventSource event.
I have a non good solution deestroying the calendar before drawing if exists, but I lose the view and day shown. Is not a good solution.
Here is my code:
var calendar;
var startDateSelected;  //YYY-MM-DD
var endDateSelected;    //YYY-MM-DD
var evTittleSelected;

//Example data
function getCalendarEvents() {
    return [{
        title: 'example1',
        start: '2019-07-15 12:00:00'
    }, {
        title: 'Example2',
        start: '2019-07-06 12:00:00',
        end: '2019-07-10 18:00:00'
    }];
}

document.addEventListener('DOMContentLoaded', function () {
    drawCalendar();
});

function drawCalendar() {
    var events = getCalendarEvents();
    var calendarEl = document.getElementById('calendar');
    if(calendar != undefined) calendar.destroy();
    calendar = new FullCalendar.Calendar(calendarEl, {
    plugins: ['interaction', 'dayGrid', 'timeGrid'],
        locale: 'es',
        selectable: true,
        editable: true,
        header: {
            left: 'prevYear,prev,next,nextYear today',
            center: 'title',
            right: 'dayGridMonth,timeGridWeek,timeGridDay'
        },
        select: function (info) {
            startDateSelected = moment(info.startStr).format("DD-MM-YYYY HH:mm:ss");
            endDateSelected = moment(info.endStr).format("DD-MM-YYYY HH:mm:ss");
            alert('de ' + startDateSelected + ' a ' + endDateSelected);
        },
        eventClick: function(info) {
            evTittleSelected = info.event.title;
            startDateSelected =  moment(info.event.start).format("DD-MM-YYYY HH:mm:ss");
            endDateSelected =  moment(info.event.end).format("DD-MM-YYYY HH:mm:ss");
            alert('de ' + startDateSelected + ' a ' + endDateSelected);
        },
        events: events
    });
    calendar.render();
}

I tried to changing event source like this:
calendar.destroy();
calendar.addEventSource( events );
calendar.refetchEvents();
calendar.render();

but without an removeEventSource method it only adds new events to the calendar.
so are there any method to reload events?
New content for imptove the answer (and use the solution in comments):
I tried to implement the event feed as per either
fullcalendar.io/docs/events-json-feed or
fullcalendar.io/docs/events-function
when I put directly events received from an ajax call to my nodejs server, it loads perfect all of them (without good option to reload). So the format of my events object seems to be ok.
I use this ajax request
jQuery.ajax({
    type: 'POST',
    url: '/calendar/getCalendarEvents',
    data: {
        token: localStorage.token
    },
}).then(function success(events) {
    return events;
}, function error(err) {
    console.log(err);
})

to fill events in this format
events:  [{
    id: 1,
    title: 'others',
    start: '2019-07-12 00:00:00',
    end: '2019-07-15 00:00:00',
    color: '#a6a6a6'
}, {
    id: 2,
    title: 'any',
    start: '2019-07-12 00:00:00',
    end: '2019-07-15 00:00:00',
    color: '#4222C3'
}]

when I try to use the events-function I'm having an error:  callback is not a function error
events: function(start, end, timezone, callback) {
    jQuery.ajax({
        type: 'POST',
        url: '/calendar/getCalendarEvents',
        data: {
            token: localStorage.token
        },
        success: function(events) {
            callback(events);
        }
    });
}

Using the metod events-json-feed I have the error Failure parsing JSON but the format is the same of the first method (that works).
events: "/calendar/main/?token=" + localStorage.token

so what could I doing wrong?

A: As @ADyson comments this works fine with this solution:
var eventSources = calendar.getEventSources();
eventSources[0].remove();
calendar.addEventSource(events);
calendar.refetchEvents();

the idea is to know that eventSources is an array
but could be better using those methods:
fullcalendar.io/docs/events-json-feed or
fullcalendar.io/docs/events-function
events: function(fetchInfo, successCallback, failureCallback) {
    jQuery.ajax({
        type: 'POST',
        url: '/calendar/getCalendarEvents',
        data: {
            token: localStorage.token
        },
        success: function(events) {
            successCallback(events);
        }
    });
}

reloading events with: calendar.refetchEvents();


text:
Q: Overflowing a register mov al,0ffh
add al,5

My question is how can I know what will be the value of al after the add line with using the debugger?
And where is the reminder?
Just for the record, the value of al after those 2 lines is 0FEh
EDIT the value is 0x04h

A:
where is the reminder

Not sure what you mean by reminder, but there's a carry flag (you can read more about it here).
You can check whether a carry occurred e.g. with the JC and JNC instructions:
MOV AL,0FFh
ADD AL,5
JC there_was_carry  ; <-- this jump will be taken

MOV AL,0F0h
ADD AL,5
JC there_was_carry  ; <-- this jump will NOT be taken


text:
Q: Identify Poisson or Exponential Distribution and determine lambda I am trying to identify the distribution of my variable, $X$. It measures goals per minute of soccer players. Possible values are $[0,inf]$ and they are non integers. I believe this to be an exponential distribution because Poisson measures integers and we are dealing with the successive events over continual time not discrete.
If this is a Poisson distribution, what should I use as the data when plotting or comparing distributions? Every time I use the rate metric, I trigger an error for things like poisson.test() or fitdist(x,"pois") in R. When I use exponential distributions, everything works.
Also, is there a way to estimate $\lambda$ generally or do you do it for discrete time periods?

A: Because your variable is a count that you are expressing as a rate, the Poisson distribution would be a natural choice. If $Y$ represents the number of goals scored by player $i$, you could model $Y_i \sim \mbox{Poisson}(N_i\lambda)$, where $N_i$ is the total number of minutes that this player was on the field, and $\lambda$ is the rate parameter that can be interpreted as goals per minute.
You might find it useful to read about Poisson processes. The example in that link of modeling meteors per minute might be similar to your question here.


text:
Q: Why does Puma respond slow or hang in clustered mode on Ruby 2.5.4 I'm adding this question because it took me a long time to even figure out that it was caused by upgrading to Ruby 2.5.4.  I'm not sure of the minimal case that can reproduce this issue, but I'm running a Rails 5 app on Puma 3.11 in clustered mode in a docker container on a Kubernetes cluster managed by Cloud66 in Google Cloud Platform.
When I start the server in clustered mode (which has been our default configuration for years), on ruby 2.5.4, the server takes a minute or more to respond, or more often never responds at all, even to a static file request (i.e. curl localhost:3000/404.html)
I found this bug that I believe is related (but could be a coincidence, since nobody else has reported this specific behavior in relation to it): https://github.com/puma/puma/issues/1674
Is this a ruby bug?  Are others experiencing this?  Is there a workaround (aside from reverting to Ruby 2.5.3)?

A: It turns out this bug was reported and I missed it because it's closed already as fixed in Ruby 2.5.5! https://github.com/puma/puma/issues/1744
(Unfortunately there is not a 2.5.5 tag in the ruby repository on dockerhub yet, but the 2.5 tag does include the fix already)


text:
Q: Codeigniter: Pass variable to the View I have to table article and table comment. In the home page I want to see how many comment for earch article.
Model
function show_latest_article($start,$display,$cate)
{
    $query=  $this->db->get_where('news_news', array('News_Cate_ID'=>$cate),$start,$display);
    if($cate==0)
    {
         $query=  $this->db->get_where('news_news',$start,$display);
    }

    return $query->result();
}
     function count_comment($id)
    {
        $query = $this->db->get_where('comment',array('comment_article_id'=>$id) );

         return $query->num_rows();

    }

Controller
 function index() {
        $this->load->model('article');
        $data=array('article'=>$this->article->show_latest_article(0,8,1),
                    'sidebar'=>$this->article->side_bar(9),
                    'count_comment'=> $this->article->count_comment($id),

            );

        $this->load->view('page/index',$data);

    }

In the view I have this
    foreach($article as $art)
{
    echo $art->title."
";
    $id= $art->id;
    // I want to echo number of comment here.
   // Or I want to call function count_comment($id)
}

A:     $this->load->model('article');
    $data['article'] = $this->article->show_latest_article(0, 8, 1);
    $data['sidebar'] => $this->article->side_bar(9);
    $data['count_comment'] => $this->article->count_comment($id);
    $this->load->view('page/index', $data);

And it should work.

A: Controller :
 function index() {
    $this->load->model('article');
    $articles =  $this->article->show_latest_article(0,8,1);
    $count_comments = Array();
    for($i=0;$i<count($articles);$i++){
        $count_comments[$i] = $this->article->count_comment($articles->$id);
    }
    $count_comments =
    $data=array('article'=>$articles,
                'sidebar'=>$this->article->side_bar(9),
                'count_comment'=> $count_comments);

    $this->load->view('page/index',$data);

 }

In the View :
$i=0;
foreach($article as $art)
{

    echo $art->title."
";
    $id= $art->id;
    echo $count_comment[$i];
    $i++;
}

A: First of all in your controller you get count_comment only for specific article ID and not for all articles so you cant do foreach to display comment count of each article.
You need to setup you model better and in model function show_latest_article to use JOIN comments table and do count comment in query.
I will help you with query if you provide me more info about database table of article and comments.
SELECT
    article.*,
    COUNT(comment.id),0) AS numberOfCommments

FROM article
LEFT JOIN comment
ON comment.article_id = article.id

GROUP BY article.id

A: I am writing this answer as you provided code. It could be more simpler if you give more database details. Try below code
function index() {
    $this->load->model('article');
    $articles = $this->article->show_latest_article(0,8,1);

    foreach($articles as $article)
    {
        $article->comment_count = $this->article->count_comment($article->id);
        $all_article[] = $article;
     }

     $data=array('article'=>$all_article,
                'sidebar'=>$this->article->side_bar(9)
        );

    $this->load->view('page/index',$data);

}

On view
foreach($article as $art)
{
    echo $art->title."
";
    $id= $art->id;
    echo $art->comment_count;

}

A: It's not so clear, where the $id variable come from, but I suggest to join the comments table to your article. It's not a best practice to make queries within loops.
In your model:
public function show_latest_article($ids = array())
{
    return $this->db
        ->select('articles.*, COUNT(comments.id) as comment_count')
        ->where_in('articles.id', $ids) // You can skip this
        ->join('comments', 'comments.article_id = articles.id', 'left')
        ->group_by('articles.id')
        ->get('articles')
        ->result();
}

In your controller:
public function index()
{
    $data['articles'] = $this->article->show_latest_article(array(0, 8, 1));
    $this->load->view('page/index', $data);
}

Just change the field name according to database columns. Also you can skip the where_in condition. (I'm not sure what the three number stands for).
Then in your view, you can simply access the field:
$art->comment_count
EDIT: According to your comment:
$this->db
    ->select('a.*, (SELECT COUNT(*) FROM comment c WHERE c.comment_article_id = a.News_News_ID ) as counta')
    ->get('news_news')
    ->result();

A: Data is passed from the controller to the view by way of an array or an object in the second parameter of the view loading function. Here is an example using an array:
$data = array(
           'title' => 'My Title',
           'heading' => 'My Heading',
           'message' => 'My Message'
      );
$this->load->view('blogview', $data);

Also below is the example for object
$data = new Someclass();
$this->load->view('blogview', $data);

PLEASE NOTE: Note: If you use an object, the class variables will be turned into array elements.
You can find out more from below ref URL
Ref: https://ellislab.com/codeigniter/user-guide/general/views.html


text:
Q: CREATE FUNCTION for "Geocode" failed because T-SQL and CLR types for return value do not match I am trying to geocode addressed from a table and found a good example here:
How to store geocoded address information into the database
or this code
using System.Net;
using System.Runtime.Serialization;
using System.Runtime.Serialization.Json;
using System.Web;
using System.Data.SqlClient;
using Microsoft.SqlServer.Types;
using System.ServiceModel.Web;

namespace ProSQLSpatial
{
public partial class GoogleMaps
{
    /// <summary>
    ///
    /// </summary>
    /// <param name="address"></param>
    /// <returns></returns>
    public static GeoResponse GetGeoCodedResults(string address)
    {
        string url = string.Format(
                "http://maps.google.com/maps/api/geocode/json?address={0}&region=dk&sensor=false"

                );
        var request = (HttpWebRequest)HttpWebRequest.Create(url);
        request.Headers.Add(HttpRequestHeader.AcceptEncoding, "gzip,deflate");
        request.AutomaticDecompression = DecompressionMethods.GZip | DecompressionMethods.Deflate;
        DataContractJsonSerializer serializer = new DataContractJsonSerializer(typeof(GeoResponse));
        var res = (GeoResponse)serializer.ReadObject(request.GetResponse().GetResponseStream());
        return res;
    }
}

[DataContract]
public class GeoResponse
{
    [DataMember(Name = "status")]
    public char Status { get; set; }

    [DataMember(Name = "results")]
    public CResult[] Results { get; set; }

    [DataContract]
    public class CResult
    {
        [DataMember(Name = "geometry")]
        public CGeometry Geometry { get; set; }

        [DataContract]
        public class CGeometry
        {
            [DataMember(Name = "location")]
            public CLocation Location { get; set; }

            [DataContract]
            public class CLocation
            {
                [DataMember(Name = "lat")]
                public double  Lat { get; set; }

                [DataMember(Name = "lng")]
                public double Lng { get; set; }
            }
        }
    }

    public GeoResponse()
    { }
}

I created the assembly in SQL Server and tried to create a function based on the assembly by:
CREATE FUNCTION dbo.Geocode
    (@Address nvarchar(4000))
RETURNS nvarchar(4000)
AS EXTERNAL NAME [test2].[ProSQLSpatial.GoogleMaps].[GetGeoCodedResults];
GO

but I get the error message

Msg 6551, Level 16, State 2, Procedure Geocode, Line 1
  CREATE FUNCTION for "Geocode" failed because T-SQL and CLR types for return value do not match.

I have done searching and I can't figure it out. I have tried changing data types, but still get the same message. Any help would be greatly would make my day. Thanks

A: This is a working example suited for your case:
The C# code (removed the web-stuff for simplicity)
using Microsoft.SqlServer.Server;
using System.Collections;
using System;

namespace ProSQLSpatial
{
    public partial class GoogleMaps
    {
        [SqlFunction(FillRowMethodName="FillRow")]
        public static IEnumerable GetGeoCodedResults(string address)
        {
            if (address == "test1")
                yield return new GeoResponse { lat = 0.1d, lng = 0.2d };
            else
                yield return new GeoResponse { lat = 0.2d, lng = 0.1d };
        }

        public static void FillRow(Object obj, out double lat, out double lng)
        {
            var entry = (GeoResponse)obj;
            lat = entry.lat;
            lng = entry.lng;
        }
    }

    public class GeoResponse
    {
        public double lat;
        public double lng;
    }
}

And here we have the SQLServer commands to register the dll and function:
CREATE ASSEMBLY TestLib FROM 'C:\Temp\TestLib.dll'
go

CREATE FUNCTION GeoCode(@address nvarchar(4000))
RETURNS TABLE (lat float, lng float)
EXTERNAL NAME [TestLib].[ProSQLSpatial.GoogleMaps].[GetGeoCodedResults]
GO

Some testing code to see if it does the trick:
create table addresses (id int identity(1, 1) primary key, [address] nvarchar(4000))
go

insert into addresses([address]) values ('test1'), ('test2')
go

select *
from addresses x
cross apply dbo.GeoCode(x.address)

select * from dbo.GeoCode('test1')

Seems to do the trick over here.


text:
Q: Sort categories by name with array in PHP Armstuff > xxxxx
Uncategorized
Biler > test
HOVED > SUB
Computere > Software
Smykker
Computere > Komponenter > RAM
sss > bbb > kkk
Computere > Komponenter > Harddiske
gg
Computere > Gadgets
Biler > Ekstraudstyr
sss > ddd

This is a list of my categories, outputted by this code:
<?php
foreach($categories as $category)
{
    echo $category['name'] . " <br />";
}
?>

Now the $categories sub category names gets defined correctly, previously in the code by:
foreach($categories as &$category)
{

    $parent = $category['parent'];
    while($parent > 0)
    {
        $parent_row = $db->select('name', 'paraent')->from('categories')->where('id', '=', $parent)->execute()->as_array();
        $parent_row = $parent_row[0];
        $category['name'] = $parent_row['name'] . " > {$category['name']}";
        $parent = $parent_row['parent'];

    }
}

I wish the output to output alphabetic, so from the above example, it should output something like :
Armstuff > xxxxx
Biler > test
Biler > Ekstraudstyr
Computere > Gadgets
Computere > Komponenter > Harddiske
Computere > Komponenter > RAM
Computere > Software
gg
HOVED > SUB
Smykker
sss > bbb > kkk
sss > ddd
Uncategorized

I tried the simply sort(), asort() but they wouldnt work out for me. How can i do this? Thanks in forward

A: Try usort because you can define your own comparer (http://at2.php.net/manual/de/function.usort.php)
Example:
function cmpCategories($a, $b) {
    if ($a["name"] == $b["name"]) {
        return 0;
    }
    return ($a["name"] < $b["name"]) ? -1 : 1;
}

usort($categories, "cmpCategories");


text:
Q: django: filter queryset when 2 fields have same value I have a model which has 2 fields like,
pickup_station_id = models.IntegerField(null=True)
drop_station_id = models.IntegerField(null=True)

I want a filter in admin which can filter the queryset based on,

*

*pickup and drop ids are different

*pickup and drop ids are same

How can I get a queryset based on these conditions?
I mean, something like this,
Mymodel.objects.filter(pickup_station_id==drop_station_id)

Mymodel.objects.filter(pickup_station_id!=drop_station_id)

A: You can refer to a field with an F-expression [Django-doc]. So we can write it like:
from django.db.models import F

Mymodel.objects.filter(pickup_station_id=F('drop_station_id'))
We can negate a query by using a Q-object [Django-doc]:
from django.db.models import F, Q

Mymodel.objects.filter(~Q(pickup_station_id=F('drop_station_id')))
Here the tilde (~) means we negate the condition that the Q object represents.


text:
Q: Using WiX, Windows Services are not installed after a downgrade While testing the downgrade functionality of one of our WiX-built MSIs, I have noticed something odd.
I have allowed downgrades in the MajorUpgrade element and I have scheduled that element to be afterInstallInitialize (but I have tried it thoroughly with afterInstallValidate and I experience the same problem; we can't have it after that action, but I thought I'd test it).
Many of the files (e.g. the DLLs in our Service's bin folder) are of a higher version, with each release; therefore, the version we are downgrading to includes files of a lower version. Yet all of those files are installed fine, during the downgrade, apart from the Service EXE files; further, the Services are also not installed in Windows.
Considering all of the above, after spending two days on this problem, and after much searching, I appear to be at a loss.
I have tried two things that seem to provide some hope:
1) I have tried setting the REINSTALLMODE property to amus. This ensures that the EXE files are installed, along with the Windows Services. But most things I read about that property warn against using it, and I even have to surpress ICE40, in order to get my package to build, when setting that property. This all concerns me, as I am not sure what negative effects could be missed, if I use this property in my MSI files.
2) When I remove the KeyPath attribute from the File elements that mark up the Service EXE files and place that attribute on the Component element instead, the Service EXE files are installed onto the system during the downgrade, but the Services are still not installed in Windows. After looking into this, it seems that the KeyPath attribute must be on the File element, if I'd like Services to be installed. So it seems to me as if this idea will not help.
Any help or advice would be very much appreciated. We really could do with providing downgrade functionality.
Thank you all for your time.

A: MSI is essentially opposed to the idea of downgrades. Once a file is on the machine, MSI tries very hard to keep the latest version of the file around as, among other reasons, downgrading the file can re-introduce a security vulnerability. I'd suggest not directly supporting downgrades; instead, you can show a message that tells the user to uninstall the higher version first.

A: My solution was to use Burn to provide the 'downgrade' functionality using a custom bootstrapper application.
The bootstrapper detects, downloads, and then installs the new version. In the case of a downgrade it performs an uninstall prior to the install. However, this requires that you execute the bootstrapper of the currently installed version to get the ability to uninstall.
You then also need to worry about any state that will be removed as a consequence of uninstalling, this needs to be preserved the same way as you would during an upgrade.

A: Using Wix, to allow downgrading and still have the Windows Service install properly on downgrade, use the following combination:
<Wix ...>
  <Product ...>
    <Property Id="REINSTALLMODE" Value="amus" />
    <MajorUpgrade Schedule="afterInstallInitialize" AllowDowngrades="yes" />

I was also using WixSharp to generate the .wxs file and used this code to do so:
// https://learn.microsoft.com/en-us/windows/win32/msi/reinstallmode
// a = Force all files to be reinstalled, regardless of checksum or version.
// m = Rewrite all required registry entries from the Registry Table that go to the HKEY_LOCAL_MACHINE or HKEY_CLASSES_ROOT registry hive. Rewrite all information from the Class Table, Verb Table, PublishComponent Table, ProgID Table, MIME Table, Icon Table, Extension Table, and AppID Table regardless of machine or user assignment.Reinstall all qualified components.When reinstalling an application, this option runs the RegisterTypeLibraries and InstallODBC actions.
// u = Rewrite all required registry entries from the Registry Table that go to theHKEY_CURRENT_USER or HKEY_USERS registry hive.
// s = Reinstall all shortcuts and re-cache all icons overwriting any existing shortcuts and icons.
project.AddXml("Wix/Product", "<Property Id=\"REINSTALLMODE\" Value=\"amus\" />");

// Allow downgrading versions
// https://wixtoolset.org/documentation/manual/v3/xsd/wix/majorupgrade.html
project.AddXml("Wix/Product", "<MajorUpgrade Schedule=\"afterInstallInitialize\" AllowDowngrades=\"yes\" />");

See also:

*

*https://learn.microsoft.com/en-us/windows/win32/msi/reinstallmode

*https://wixtoolset.org/documentation/manual/v3/xsd/wix/msiproperty.html

*https://wixtoolset.org/documentation/manual/v3/xsd/wix/majorupgrade.html


text:
Q: no match for operator[] error I've been experimenting with operating overloading in C++ and I tried using templates. But I got this error: error: no match for 'operator[]' in 'a[4]'
Here's my code:
#include "JSE.h"
#include <iostream>
using namespace std;

struct obj{
    int l;
    template<typename varname>
    varname operator[] (int n){
        return (this->l)+n;
    }
};

int main(void){
    obj a;
    a.l=20;
    cout<<a[4];
    return 0;
}

And I only get this error if I use templates. For example, this code works:
#include "JSE.h"
#include <iostream>
using namespace std;

struct obj{
    int l;
    int operator[] (int n){
        return (this->l)+n;
    }
};

int main(void){
    obj a;
    a.l=20;
    cout<<a[4];
    return 0;
}

What's causing the error and how can I fix it?
Note: I really want to keep the template as I will use it with the operator overloading in a future project.

A: The problem is that for the first program the compiler is unable to determine the return type of the operator.
You could call the operator only like
obj a;
a.l=20;
std::cout<< a.operator []<int>( 4 ) << std::endl;

Change the class definition the following way
template<typename varname>

struct obj{
    varname l;
    varname operator[] (int n){
        return (this->l)+n;
    }
};

And in main there will be code like
obj<int> a;
a.l=20;
cout<<a[4];

A: In order for template deduction to work the compiler must be able to somehow deduce what the types are that you are using.
template<typename varname>
varname operator[] (int n){
    return (this->l)+n;
}

Does not allow this as the only thing that you are templating is the return type.  The compiler has no way of know what type you want as a return type and so you are getting error like this.
If you instead use the template type in the function parameter then the compiler can deduce the template type as it can use the type passed to the function.
#include <iostream>
using namespace std;

struct obj{
    int l;
    template<typename varname>
    varname operator[] (varname n){
        return (this->l)+n;
    }
};

int main(void){
    obj a;
    a.l=20;
    cout<<a[4];
    return 0;
}

Live example


text:
Q: Escaping % symbol in MySQL with PHP i have a simple search box but I am trying to avoid the result page returning all results in table when the query is %. how can that be done?

A: I think you want to use \%...
In your PHP,
$query = str_replace ( '%' , '\%' , $query )

$sql = "SELECT * FROM table WHERE column LIKE '%" . mysqli_real_escape_string($query) . "%'"

A: Are you sanitizing your inputs?
You can start with mysqli_real_escape_string()
$query = "SELECT * FROM table WHERE column LIKE '" . mysqli_real_escape_string($input) . "'";


text:
Q: Is there a better way to read unzipped data into a slice? I'm reading gzip data from a http request like this:
gzr, err := gzip.NewReader(resp.Body)
handle(err)

And then conservatively allocating a slice for the unzipped data.
cl := resp.Header.Get("Content-Length")
icl, err := strconv.Atoi(cl)
handle(err)
ubs := make([]byte, icl*3)

And finally trimming the slice after reading
_, err = gzr.Read(ubs)
ubs = bytes.TrimRightFunc(ubs, sliceFunc)

Is there a better way to do this ?

A: For starters, .Read returns the numbers of bytes read, so you can do something like:
n, err = gzr.Read(ubs)
ubs = ubs[:n]

Also you can use a bytes.Buffer pool and do something like:
buf := getBufferFromPool()
io.Copy(buf, gzr)


text:
Q: Error while publishing in R pubs When I am trying to  publish my work in R Pubs I am getting an error:
Error in function (type, msg, asError = TRUE)  :
  SSL certificate problem, verify that the CA cert is OK. Details:
error:14090086:SSL routines:SSL3_GET_SERVER_CERTIFICATE:certificate verify failed
Calls: rpubsUpload ... <Anonymous> -> .postForm -> .Call -> <Anonymous> -> fun
Execution halted

Is there anyway to resolve it ?

A: I had the similar problem. I copied the options(rpubs.upload.method = "internal") as described by @Tyler Rinker at the end of the .RProfile. The .RProfile file was located in \library\base\R folder of installation directory.

A: I had also the same error message.
I found solution for my problem on Rstudio support page.
In short, I added:
options(rpubs.upload.method = "internal")
options(RCurlOptions = list(verbose = FALSE, capath = system.file("CurlSSL", "cacert.pem", package = "RCurl"), ssl.verifypeer = FALSE))

to R_HOME/etc/Rprofile.site.
And do not forget to change permissions for this file.
My system:
sysname    release  machine
"Windows"  "7 x64"  "x86-64"

R version 3.1.2 (2014-10-31) -- "Pumpkin Helmet"

A: Add an .Rprofile file in the directory you are sending from and place this line:
options(rpubs.upload.method = "internal")

in the .Rprofile or RProfile.site files.

A: You need to have an account in Rpubs. Also i have copied options(rpubs.upload.method = "internal") in .RProfile as suggested above and after doing that i just ran my .Rmd file and then published and it works fine.


text:
Q: Powershell update a variable using another variable reference I'm trying to concatenate a variable reference inside another string but it keeps showing wrong values.
Basically I intend to update variable $arq value acording to variable $version, without having to reset $arq.
I'm using [ref] but not sure it's the best way to do so.
I've tryed the following so far.
$downloadSource = "\\domain.or.ip\folder"
$version = "0.0.0"
$arq = "file_name_$([ref]$version)`_filename_continuation.zip"

function UpdateVersion {

    (Get-ChildItem -name "$downloadSource\file_name*").Split('_')[2]

    }

$version = UpdateVersion

echo $version
echo $arq

Variable $version is being updated correctly.
But $arq is receiving the wrong value:

"file_name_System.Management.Automation.PSReference`1[System.String]_filename_continuation.zip"

I tried changing $arq as follows
$arq = "file_name_" + $(($versaoEsperada).value) + "`_filename_continuation.zip"

But the same wrong value is shown.
Would you guys help me, please?
Thanks


text:
Q: Unable to access userDefaults with standard I have trouble with UserDefaults.
I already tried userDefaults.standard but it's not working. The userDefeaults with standard shows an error:

"which is "Static member 'standard' cannot be used on instance of type 'UserDefaults'"

if user != nil {
    if userDefaults.standard.object
}

Static member 'standard' cannot be used on instance of type 'UserDefaults'

Why can not accept the standard with userDefaults?

A: Here is how you can work with UserDefaults.
Get a reference to user defaults:
let defaults = UserDefaults.standard

Set an object for key "age":
defaults.set(31, forKey: "age")

Unwrap the value of the stored key. If it is nil (key does not exist), it will not enter the block.
if let object = defaults.object(forKey: "age") {
}


text:
Q: Unable to view Hystrix metrics in Dropwizard app via hystrix-metrics-event-stream servlet I have a Dropwizard 0.8.1 app to which I have added a number of HystrixCommand classes for calling out to various external services. I now want to visualize stats related to calls to those services, but I can't seem to get my app to play nice with the Hystrix Dashboard. All the documentation seems to imply that if I get the hystrix-metrics-event-stream servlet working in my app then everything should Just Work, but when I call my servlet endpoint directly (curl  http://localhost:8080/hystrix.stream) I just get a long stream of ping: lines, implying that there are no metrics available to be published. I have a cron job repeatedly calling my HystrixCommand objects to try to generate some stats, to no avail.
Is there something I'm not doing? I have added the dependency to my pom.xml:
<dependency>
    <groupId>com.netflix.hystrix</groupId>
    <artifactId>hystrix-metrics-event-stream</artifactId>
    <version>1.4.5</version>
</dependency>

I have integrated the servlet into Dropwizard in App.java:
public void run(final AppConfig configuration, final Environment environment) throws Exception {
...
environment.getApplicationContext().addServlet("com.netflix.hystrix.contrib.metrics.eventstream.HystrixMetricsStreamServlet", "/hystrix.stream");

Is it possible that I need to manually publish metrics data to be picked up by the HystrixMetricsPoller? Or maybe I need to tweak some config for my dev environment? Help is appreciated!

A: Sorted it! It turned out that the version of the hystrix-metrics-event-stream artifact was 1.4.5 but the version of hystrix-core was 1.3.8. I didn't spot it at first because it was stored in another POM file. I'm now using exactly the same version across all hystrix packages and getting data just fine from the hystrix.stream servlet.
As a related aside, I also found hystrix-dropwizard-bundle which looks like a much easier and flexible way to integrate Dropwizard with Hystrix for most people than doing it from scratch or using something as complex as Tenacity. It includes support for HystrixCodaHaleMetricsPublisher which might be of use to people using Dropwizard metrics (we're not).


text:
Q: for loop runs only once in angularjs In Js file:
$scope.isCheckboxChecked = function() {
        var chks = document.getElementsByName('chk[]');
        for (var i = 0; i < chks.length; i++)
        {
            if (chks[i].checked)
            {
                $scope.checkBoxClicked = true;
                $('#btnUpdateData').attr("data-target", "#update-modal");
                $('#btnUpdateData').attr("data-toggle", "modal");
                break;
            }
            if ($scope.checkBoxClicked == false)
            {
                alert("Please select at least one checkbox");
            }
        }
    }

In HTML

        <button type="button" id="btnUpdateData" class="btn btn-info" ng-click="isCheckboxChecked()">Update</button>

This code checks if the checkbox is checked only once.
once the checkbox is unchecked, I want the for loop to run again.

A: Here's a Plunkr example of how you could watch a checkbox's statechange and do something when it changes:
https://plnkr.co/edit/kyEv7IyAXGFRdZjaD4vM?p=preview
var app = angular.module('plunker', []);

   app.controller('MainCtrl', function($scope) {
     $scope.$watch("testCheckBox", function(newVal, oldVal){
       alert('Checkbox changed!')
   });

});

Html:

Check box test

 <input type="checkbox" name="testCheckbox" ng-model="testCheckBox"></input>


text:
Q: Why scaleToFill not filling the whole screen? I would like to use an image as the background of the app.
struct DetailView: View {

    var borderWidth: CGFloat = 0

    var body: some View {

        // ZStack: Background, ScrollView(vertical)
        ZStack {
            Image("background_green").resizable().scaledToFill().opacity(0.8)
                .frame(width:UIScreen.main.bounds.width, height:UIScreen.main.bounds.height)
            VStack {

            }.frame(width: UIScreen.main.bounds.width, height:UIScreen.main.bounds.height)
        }

    }
}

How come there are still some white space at the top?

A: You should ignore safe area, like
var body: some View {

    // ZStack: Background, ScrollView(vertical)
    ZStack {
        Image("background_green").resizable().scaledToFill().opacity(0.8)
            .edgesIgnoringSafeArea(.all)              // << here !!

        VStack {

        }.frame(width: UIScreen.main.bounds.width, height:UIScreen.main.bounds.height)
    }
}


text:
Q: How can I defer processing during apache / mod_perl page rendering? I have an apache2 / mod_perl website. On one page, I need to do some server/server communication via SOAP.
The results of this communication are not required for the rendering of the page (but user input is required to trigger this communication).
The SOAP communication is very slow.
So what I want to do is process and print the page for the user, then do all the SOAP stuff behind the scenes.
What's the best way to achieve this? start some fork? write the job to a file and have a cronjob pick it up?
Thanks

A: There are two types of solutions: First you can do what Randal Schwartz suggested here. Second you could use a Message Queue like Beanstalk or Gearman. Beanstalk has a Perl Client and is now persistent and is ideal for lightweight stuff. Gearman on the other hand has more features, more worked on. There is also TheSchwartz - use it if you can do without too much documentation. cron is ideal for systematically repeating tasks. For the kind of application you have, it appears that Schedule::At might be more appropriate if you prefer a more generic "message-queue"
Also see an old StackOverflow Thread here


text:
Q: C# Do I have to unsubscribe from WMI events before closing? As the title says, In my code I have registered a callback function when a program launches using WMI:
ManagementEventWatcher Watcher = new ManagementEventWatcher(new WqlEventQuery("SELECT * FROM Win32_ProcessStartTrace WHERE ProcessName='ExampleApp.exe'"));

Before my application exits do I have to call:
Watcher.Stop();
Watcher.Dispose();

Or is it done automatically. The reason I ask is that my application that is subscribing to the event will be Process.Kill() by another application, rather than gracefully terminating so it doesn't not have the chance to properly unsubscribe.
Thanks


text:
Q: how to change the defult boolen value in flutter I'm using bool value as default as false and after my, onpress event, it's changed but refreshes the screen it comes back to default value again how to fix this.
 class _MarketState extends State<Market> {
  final _database = FirebaseDatabase.instance.ref().child('data/market/');
  bool _sortvalue = false;

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: Scrollbar(
        child: StreamBuilder(
        stream: _database.onValue,
        builder: (context, snapshot) {
          final valudisp = <Card>[];
          if (snapshot.hasData) {
            final firstdata = (snapshot.data! as DatabaseEvent)
                .snapshot
                .value as Map<Object?, dynamic>;
            final data = firstdata.values.toList();
            if (_sortvalue == false) {
              data.sort((a, b) => a['Quantity'].compareTo(b['Quantity']));
            } else {
              data.sort((a, b) => a['tradep'].compareTo(b['tradep']));
            }

            final sdata = List.from(data.reversed);
            Set<Object> dataset = Set.from(sdata);
            dataset.forEach((element) {
              final datalast = element as Map<dynamic, dynamic>;
              final coinname = datalast['namedata'];
              final diff = datalast['dif'];
              final time = datalast['Time'];
              final Quantity = datalast['Quantity'];
              final tradep = datalast['tradep'];
              Color signalcolor =
                  diff > 0 ? Color(0xff008b45) : Color(0xffB3000C);
              final displaycard = Card(...);
      floatingActionButton: FloatingActionButton(
        child: Icon(
            _sortvalue ? Icons.bar_chart_rounded : Icons.attach_money_rounded),
        onPressed: () {
          setState(() => _sortvalue = !_sortvalue);
        },

------------------------------------------------------