text:
Q: Detect/Verify the encoding of an XML file following the w3c recommandation Well,
I looked for c# XML encode detector following the W3C recommendations, but I did not found it.
Several solutions are around the web, but none that strictly follows thw W3C recommendations above.
Shortly, W3C says: "Each XML entity not accompanied by external encoding information and not in UTF-8 or UTF-16 encoding must begin with an XML encoding declaration, in which the first characters must be "< ?xml". [...] a processor can detect, after two to four octets of input, which is the encoding."
Does anybody has a c# implementation of such algorithm?

A: Starting from the java implementation proposed by A. Hristov here, I wrote a C# implementation integrated with the suggestions taken from the TextFileEncodingDetector project. I hope it will be useful for the community.
Note: the code seems to be long but there is only one public method.
using System;
using System.IO;
using System.Xml;
using System.Text;
using System.Text.RegularExpressions;

public class XmlEncodingDetector
{

    /// Detect the XML encoding by reading both the file stream as text-based and the encoding pseudoattribute of the XML header (if present)
    /// The encoding is detected using the guidelines specified in the http://www.w3.org/TR/xml/#sec-guessing' (XML W3C Specification).
    ///
    /// Returns the detected encoding or null if not detected</returns>
    public static Encoding DetectXmlFileEncoding(string xmlFileName)
    {
        using (FileStream xmlFileStream = File.OpenRead(xmlFileName))
        {
            return DetectXmlFileEncoding(xmlFileStream);
        }
    }

    /// Detect the XML encoding by reading both the file stream as text-based and the encoding pseudoattribute of the XML header (if present)
    /// The encoding is detected using the guidelines specified in the http://www.w3.org/TR/xml/#sec-guessing' (XML W3C Specification).
    ///
    /// Returns the detected encoding or null if not detected</returns>
    public static Encoding DetectXmlFileEncoding(FileStream xmlFileStream)
    {
        long originalPos = -1;
        Encoding encodingFound1 = null;
        Encoding encodingFound2 = null;
        try
        {
            originalPos = xmlFileStream.Position;

            // Reading a binary sample of the file in order to parse it
            byte[] sample = new byte[xmlFileStream.Length > 0x100 ? 0x100 : xmlFileStream.Length];
            xmlFileStream.Read(sample, 0, sample.Length);

            // look for the BOM of the file in the read sample
            encodingFound1 = DetectBOMBytes(sample);

            // if the encoding was not detected due to a missing or unrecognizable BOM, try to detect from the binary representation of the string "<?xml"
            Boolean checkPseudoAttribute = false;
            if (encodingFound1 == null)
            {
                if (sample[0] == (byte)0x00 && sample[1] == (byte)0x3C && sample[2] == (byte)0x00 && sample[3] == (byte)0x3F)
                {
                    // UTF-16BE or big-endian ISO-10646-UCS-2 or other encoding with a 16-bit code unit in big-endian order and ASCII characters encoded as ASCII values
                    // (the encoding declaration must be read to determine which)
                    encodingFound1 = Encoding.BigEndianUnicode;
                    checkPseudoAttribute = true;
                }
                else if (sample[0] == (byte)0x00 && sample[1] == (byte)0x00 && sample[2] == (byte)0x00 && sample[3] == (byte)0x3C)
                {
                    // most probably utf-32BE (Encoding.GetEncoding(12001))
                    // (the encoding declaration must be read to determine which)
                    encodingFound1 = Encoding.GetEncoding(12001);
                    checkPseudoAttribute = true;
                }
                else if (sample[0] == (byte)0xFF && sample[1] == (byte)0xFE)
                {
                    encodingFound1 = Encoding.Unicode;
                }
                else if (sample[0] == (byte)0xFE && sample[1] == (byte)0xFF)
                {
                    encodingFound1 = Encoding.BigEndianUnicode;
                }
                else if (sample[0] == (byte)0x3C && sample[1] == (byte)0x00 && sample[2] == (byte)0x00 && sample[3] == (byte)0x00)
                {
                    // (the encoding declaration must be read to determine which)
                    encodingFound1 = Encoding.UTF32;
                    checkPseudoAttribute = true;
                }
                else if (sample[0] == (byte)0x3C && sample[1] == (byte)0x00 && sample[2] == (byte)0x3F && sample[3] == (byte)0x00)
                {
                    // UTF-16LE or little-endian ISO-10646-UCS-2 or other encoding with a 16-bit code unit in little-endian order and ASCII characters encoded as ASCII values
                    // (the encoding declaration must be read to determine which)
                    encodingFound1 = Encoding.Unicode;
                    checkPseudoAttribute = true;
                }
                else if (sample[0] == (byte)0x3C && sample[1] == (byte)0x3F && sample[2] == (byte)0x78 && sample[3] == (byte)0x6D)
                {
                    // UTF-8, ISO 646, ASCII, some part of ISO 8859 or any other 7-bit, 8-bit
                    // (the encoding declaration must be read to determine which)
                    encodingFound1 = Encoding.ASCII;
                    checkPseudoAttribute = true;
                }
                else if (sample[0] == (byte)0x4C && sample[1] == (byte)0x6F && sample[2] == (byte)0xA7 && sample[3] == (byte)0x94)
                {
                    encodingFound1 = Encoding.GetEncoding(37);    // IBM037 - IBM EBCDIC US-Canada"CP037";
                }
            }   // if (encodingFound1 == null)

            // Now read the encoding pseudoattribute in the XML header, if present
            encodingFound2 = GetXmlDeclaredEncoding(sample, encodingFound1 ?? Encoding.UTF8);   // if I have no info, try with the most common (sigh)
            // when not declare, w3c says it is utf-8
            if (encodingFound2 == null) encodingFound2 = Encoding.UTF8;

            // compare the 2 found encoding and decided which is the right one
            Encoding winner = null;
            if (encodingFound1 == encodingFound2)
            {
                winner = encodingFound2;
            }
            else if (encodingFound1 == null)
            {
                winner = encodingFound2;
            }
            else if (encodingFound2 == null)
            {
                winner = encodingFound1;
            }
            else if (checkPseudoAttribute)
            {
                // Fine-tune the winner encoding. This is the most heuristic part, as some encoding
                // can be overloaded. E.g. ASCII might be UTF-7, UTF-8, ISO-8859...

                if (encodingFound1.Equals(Encoding.ASCII) &&
                        (encodingFound2.Equals(Encoding.UTF7) || encodingFound2.Equals(Encoding.UTF8) || encodingFound2.HeaderName.Contains("iso-8859")))
                {
                    winner = encodingFound2;
                }
                else
                {
                    // I'm not sure here if throw an exception or accept encodingFound1 or encodingFound2,
                    // as both are not null and not equals
                    throw new XmlException(string.Format("{0} ({1}, {2})",
                            "The text encoding and the encoding pseudo-attribute of the XML header mismatch",
                            encodingFound1, encodingFound2));
                }
            }
            else
            {
                // encodingFound1 and encodingFound2 are different so none win
                throw new XmlException(string.Format("{0} ({1}, {2})",
                        "The text encoding and the encoding pseudo-attribute of the XML header mismatch",
                        encodingFound1, encodingFound2));
            }

            // return the detected encoding
            return winner;
        }
        finally
        {
            if (originalPos >= 0) xmlFileStream.Position = originalPos;
        }

    }

    #region private methods

    /// Search for the standard Begin of Message sequence to identify encoding
    /// Returns the possibily null identified encoding
    private static Encoding DetectBOMBytes(byte[] BOMBytes)
    {
        if (BOMBytes.Length < 2) return null;

        if (BOMBytes[0] == 0xFF && BOMBytes[1] == 0xFE
                && (BOMBytes.Length < 4 || BOMBytes[2] != 0x00 || BOMBytes[3] != 0x00))
            return Encoding.Unicode;            // utf-16LE - Unicode UTF-16 little endian byte order

        if (BOMBytes[0] == 0xFE && BOMBytes[1] == 0xFF)
            return Encoding.BigEndianUnicode;   // utf-16BE - Unicode UTF-16 big endian byte order

        if (BOMBytes.Length < 3) return null;

        if (BOMBytes[0] == 0xEF && BOMBytes[1] == 0xBB && BOMBytes[2] == 0xBF)
            return Encoding.UTF8;               // utf-8

        if (BOMBytes[0] == 0x2B && BOMBytes[1] == 0x2F && BOMBytes[2] == 0x76)
            return Encoding.UTF7;               // note: Character encodings such as UTF-7 that make overloaded usage of ASCII-valued bytes may fail to be reliably detected

        if (BOMBytes.Length < 4) return null;

        if (BOMBytes[0] == 0xFF && BOMBytes[1] == 0xFE && BOMBytes[2] == 0x00 && BOMBytes[3] == 0x00)
            return Encoding.UTF32;              // utf-32LE - Unicode UTF-32 little endian byte order

        if (BOMBytes[0] == 0x00 && BOMBytes[1] == 0x00 && BOMBytes[2] == 0xFE && BOMBytes[3] == 0xFF)
            return Encoding.GetEncoding(12001); // utf-32BE - Unicode UTF-32 big endian byte order

        return null;
    }

    private static Encoding GetXmlDeclaredEncoding(byte[] sample, Encoding guessedEncoding)
    {
        // capture the encoding from the xml declaraion
        string contents = contents = GetStringFromByteArray(sample, guessedEncoding);
        string pattern = "<\\?xml\\sversion=\"1.0\"\\sencoding=\"(?<encoding>[\\w|-]+)\"";
        Match m = Regex.Match(contents, pattern, RegexOptions.ExplicitCapture);

        return (m.Groups["encoding"].Success) ? Encoding.GetEncoding(m.Groups["encoding"].Value) : null;
    }

    private static string GetStringFromByteArray(byte[] message, Encoding guessedEncoding)
    {
        // try to get the encoding from the byte array
        Encoding encodingFound = DetectBOMBytes(message);

        return (encodingFound != null)
            // for some reason, the default encodings don't detect/swallow their own preambles!!
            ? encodingFound.GetString(message, encodingFound.GetPreamble().Length, message.Length - encodingFound.GetPreamble().Length)
            : (DetectUnicodeInByteSampleByHeuristics(message) ?? guessedEncoding).GetString(message);
    }

    private static Encoding DetectUnicodeInByteSampleByHeuristics(byte[] SampleBytes)
    {
        long oddBinaryNullsInSample = 0;
        long evenBinaryNullsInSample = 0;
        long suspiciousUTF8SequenceCount = 0;
        long suspiciousUTF8BytesTotal = 0;
        long likelyUSASCIIBytesInSample = 0;

        // Cycle through, keeping count of binary null positions, possible UTF-8
        // sequences from upper ranges of Windows-1252, and probable US-ASCII
        // character counts.

        long currentPos = 0;
        int skipUTF8Bytes = 0;

        while (currentPos < SampleBytes.Length)
        {
            //binary null distribution
            if (SampleBytes[currentPos] == 0)
            {
                if (currentPos % 2 == 0)
                    evenBinaryNullsInSample++;
                else
                    oddBinaryNullsInSample++;
            }

            //likely US-ASCII characters
            if (IsCommonUSASCIIByte(SampleBytes[currentPos])) likelyUSASCIIBytesInSample++;
            //suspicious sequences (look like UTF-8)
            if (skipUTF8Bytes == 0)
            {
                int lengthFound = DetectSuspiciousUTF8SequenceLength(SampleBytes, currentPos);

                if (lengthFound > 0)
                {
                    suspiciousUTF8SequenceCount++;
                    suspiciousUTF8BytesTotal += lengthFound;
                    skipUTF8Bytes = lengthFound - 1;
                }
            }
            else
            {
                skipUTF8Bytes--;
            }

            currentPos++;
        }

        //1: UTF-16 LE - in english / european environments, this is usually characterized by a
        // high proportion of odd binary nulls (starting at 0), with (as this is text) a low
        // proportion of even binary nulls.
        // The thresholds here used (less than 20% nulls where you expect non-nulls, and more than
        // 60% nulls where you do expect nulls) are completely arbitrary.

        if (((evenBinaryNullsInSample * 2.0) / SampleBytes.Length) < 0.2
        && ((oddBinaryNullsInSample * 2.0) / SampleBytes.Length) > 0.6
        )
            return Encoding.Unicode;

        //2: UTF-16 BE - in english / european environments, this is usually characterized by a
        // high proportion of even binary nulls (starting at 0), with (as this is text) a low
        // proportion of odd binary nulls.
        // The thresholds here used (less than 20% nulls where you expect non-nulls, and more than
        // 60% nulls where you do expect nulls) are completely arbitrary.

        if (((oddBinaryNullsInSample * 2.0) / SampleBytes.Length) < 0.2
        && ((evenBinaryNullsInSample * 2.0) / SampleBytes.Length) > 0.6
        )
            return Encoding.BigEndianUnicode;

        //3: UTF-8 - Martin Dürst outlines a method for detecting whether something CAN be UTF-8 content
        // using regexp, in his w3c.org unicode FAQ entry:
        // http://www.w3.org/International/questions/qa-forms-utf-8
        // adapted here for C#.
        string potentiallyMangledString = Encoding.ASCII.GetString(SampleBytes);
        Regex UTF8Validator = new Regex(@"\A("
        + @"[\x09\x0A\x0D\x20-\x7E]"
        + @"|[\xC2-\xDF][\x80-\xBF]"
        + @"|\xE0[\xA0-\xBF][\x80-\xBF]"
        + @"|[\xE1-\xEC\xEE\xEF][\x80-\xBF]{2}"
        + @"|\xED[\x80-\x9F][\x80-\xBF]"
        + @"|\xF0[\x90-\xBF][\x80-\xBF]{2}"
        + @"|[\xF1-\xF3][\x80-\xBF]{3}"
        + @"|\xF4[\x80-\x8F][\x80-\xBF]{2}"
        + @")*\z");
        if (UTF8Validator.IsMatch(potentiallyMangledString))
        {
            //Unfortunately, just the fact that it CAN be UTF-8 doesn't tell you much about probabilities.
            //If all the characters are in the 0-127 range, no harm done, most western charsets are same as UTF-8 in these ranges.
            //If some of the characters were in the upper range (western accented characters), however, they would likely be mangled to 2-byte by the UTF-8 encoding process.
            // So, we need to play stats.

            // The "Random" likelihood of any pair of randomly generated characters being one
            // of these "suspicious" character sequences is:
            // 128 / (256 * 256) = 0.2%.
            //
            // In western text data, that is SIGNIFICANTLY reduced - most text data stays in the <127
            // character range, so we assume that more than 1 in 500,000 of these character
            // sequences indicates UTF-8. The number 500,000 is completely arbitrary - so sue me.
            //
            // We can only assume these character sequences will be rare if we ALSO assume that this
            // IS in fact western text - in which case the bulk of the UTF-8 encoded data (that is
            // not already suspicious sequences) should be plain US-ASCII bytes. This, I
            // arbitrarily decided, should be 80% (a random distribution, eg binary data, would yield
            // approx 40%, so the chances of hitting this threshold by accident in random data are
            // VERY low).

            if ((suspiciousUTF8SequenceCount * 500000.0 / SampleBytes.Length >= 1) //suspicious sequences
                        && ( //all suspicious, so cannot evaluate proportion of US-Ascii
                            (SampleBytes.Length - suspiciousUTF8BytesTotal == 0)
                                || likelyUSASCIIBytesInSample * 1.0 / (SampleBytes.Length - suspiciousUTF8BytesTotal) >= 0.8
                            )
                )
                return Encoding.UTF8;
        }

        return null;
    }

    private static bool IsCommonUSASCIIByte(byte testByte)
    {
        if (testByte == 0x0A //lf
        || testByte == 0x0D //cr
        || testByte == 0x09 //tab
        || (testByte >= 0x20 && testByte <= 0x2F) //common punctuation
        || (testByte >= 0x30 && testByte <= 0x39) //digits
        || (testByte >= 0x3A && testByte <= 0x40) //common punctuation
        || (testByte >= 0x41 && testByte <= 0x5A) //capital letters
        || (testByte >= 0x5B && testByte <= 0x60) //common punctuation
        || (testByte >= 0x61 && testByte <= 0x7A) //lowercase letters
        || (testByte >= 0x7B && testByte <= 0x7E) //common punctuation
        )
            return true;
        else
            return false;
    }

    private static int DetectSuspiciousUTF8SequenceLength(byte[] SampleBytes, long currentPos)
    {
        int lengthFound = 0;

        if (SampleBytes.Length >= currentPos + 1
        && SampleBytes[currentPos] == 0xC2
        )
        {
            if (SampleBytes[currentPos + 1] == 0x81
            || SampleBytes[currentPos + 1] == 0x8D
            || SampleBytes[currentPos + 1] == 0x8F
            )
                lengthFound = 2;
            else if (SampleBytes[currentPos + 1] == 0x90
            || SampleBytes[currentPos + 1] == 0x9D
            )
                lengthFound = 2;
            else if (SampleBytes[currentPos + 1] >= 0xA0
            && SampleBytes[currentPos + 1] <= 0xBF
            )
                lengthFound = 2;
        }
        else if (SampleBytes.Length >= currentPos + 1
        && SampleBytes[currentPos] == 0xC3
        )
        {
            if (SampleBytes[currentPos + 1] >= 0x80
            && SampleBytes[currentPos + 1] <= 0xBF
            )
                lengthFound = 2;
        }
        else if (SampleBytes.Length >= currentPos + 1
        && SampleBytes[currentPos] == 0xC5
        )
        {
            if (SampleBytes[currentPos + 1] == 0x92
            || SampleBytes[currentPos + 1] == 0x93
            )
                lengthFound = 2;
            else if (SampleBytes[currentPos + 1] == 0xA0
            || SampleBytes[currentPos + 1] == 0xA1
            )
                lengthFound = 2;
            else if (SampleBytes[currentPos + 1] == 0xB8
            || SampleBytes[currentPos + 1] == 0xBD
            || SampleBytes[currentPos + 1] == 0xBE
            )
                lengthFound = 2;
        }
        else if (SampleBytes.Length >= currentPos + 1
        && SampleBytes[currentPos] == 0xC6
        )
        {
            if (SampleBytes[currentPos + 1] == 0x92)
                lengthFound = 2;
        }
        else if (SampleBytes.Length >= currentPos + 1
        && SampleBytes[currentPos] == 0xCB
        )
        {
            if (SampleBytes[currentPos + 1] == 0x86
            || SampleBytes[currentPos + 1] == 0x9C
            )
                lengthFound = 2;
        }
        else if (SampleBytes.Length >= currentPos + 2
        && SampleBytes[currentPos] == 0xE2
        )
        {
            if (SampleBytes[currentPos + 1] == 0x80)
            {
                if (SampleBytes[currentPos + 2] == 0x93
                || SampleBytes[currentPos + 2] == 0x94
                )
                    lengthFound = 3;
                if (SampleBytes[currentPos + 2] == 0x98
                || SampleBytes[currentPos + 2] == 0x99
                || SampleBytes[currentPos + 2] == 0x9A
                )
                    lengthFound = 3;
                if (SampleBytes[currentPos + 2] == 0x9C
                || SampleBytes[currentPos + 2] == 0x9D
                || SampleBytes[currentPos + 2] == 0x9E
                )
                    lengthFound = 3;
                if (SampleBytes[currentPos + 2] == 0xA0
                || SampleBytes[currentPos + 2] == 0xA1
                || SampleBytes[currentPos + 2] == 0xA2
                )
                    lengthFound = 3;
                if (SampleBytes[currentPos + 2] == 0xA6)
                    lengthFound = 3;
                if (SampleBytes[currentPos + 2] == 0xB0)
                    lengthFound = 3;
                if (SampleBytes[currentPos + 2] == 0xB9
                || SampleBytes[currentPos + 2] == 0xBA
                )
                    lengthFound = 3;
            }
            else if (SampleBytes[currentPos + 1] == 0x82
            && SampleBytes[currentPos + 2] == 0xAC
            )
                lengthFound = 3;
            else if (SampleBytes[currentPos + 1] == 0x84
            && SampleBytes[currentPos + 2] == 0xA2
            )
                lengthFound = 3;
        }

        return lengthFound;
    }

    #endregion
}


text:
Q: Why private/protected members must originate from the same class for type compatibility? In TypeScript Handbook, it says:

Private and protected members in a class affect their compatibility.
  When an instance of a class is checked for compatibility, if the
  instance contains a private member, then the target type must also
  contain a private member that originated from the same class.
  Likewise, the same applies for an instance with a protected member.
  This allows a class to be assignment compatible with its super class,
  but not with classes from a different inheritance hierarchy which
  otherwise have the same shape.

While type compatibility in TypeScript being structural (duck typing):
class Animal {
    feet: number;
}

class Size {
    feet: number;
}

let a: Animal = new Size; // Ok!

the cases for class containing protected/private members is actually nominal:
class Animal {
    private feet: number;
}

class Size {
    private feet: number;
}

let a: Animal = new Size; // Error!

Could anyone explain why this inconsistency exists in TypeScript between public and protected/private members?

A: This is by design to prevent private/protected members from being accessed from a different type.
From https://github.com/Microsoft/TypeScript/issues/7755:

Consider something like this
class Foo {
    private versionNumber = 10;

    public compareTo(other: Foo) {
        return this.getVersion() === other.getVersion();
    }

    private getVersion() {
        return this.versionNumber;
    }
}

class Bar {
    private myName = 'default;'
    public compareTo(other: Bar) {
        return this.myName === other.myName;
    }

    private getVersion() {
        /* ... DANGEROUS CODE HERE ...*/
        return -1;
    }
}

By inspection, Bar#getVersion is never invoked -- it's a private
  method and there are no calls to it from the originating class. That
  inspection ought to be sufficient for code that doesn't actively try
  to work around the typechecker.
But this code does invoke Bar#getVersion:
let f = new Foo();
let b = new Bar();
f.compareTo(b);

redpajama_set_name: RedPajamaStackExchange


text:
Q: Deriving XPath for accessing table elements I am trying to scrape the table from this website using HtmlAgilityPack and a C# Console App.
I am able to scrape the names of the stocks in Column 2 (ex: EDAP TMS ADR (EDAP) but I am not being able to get the correct XPath for any of the values from the Price, Chg, Chg% columns.
For ex:
My XPath for the names column works perfectly as:
"//*[@id=\"column0\"]//div//table//tr//td//a"

What would be the XPath for the Price, Chg, Chg% columns?
Can you help me understand how you would derive it?

A: Here is the xpath to get the desired column output, based on column name.
For price: Getting price from 4th row.
//div[@class='mdcNarrowM']//table//tr[4]/td[count(ancestor::table[1]//tr[1]/td[.='Price']/preceding-sibling::td)+1]

General Notation in this case: (update the row number and column names as per your need) Tested for all the columns in that table.
//div[@class='mdcNarrowM']//table//tr[row_number_goes_here]/td[count(ancestor::table[1]//tr[1]/td[.='column name goes here']/preceding-sibling::td)+1]

To get all the rows (except the header row) use this below xpath.
//div[@class='mdcNarrowM']//table//tr[not(td[@class='colhead'])]/td[count(ancestor::table[1]//tr[1]/td[.='Price']/preceding-sibling::td)+1]


text:
Q: No Scratch Org Definition Configuration Value For Contacts to Multiple Accounts There is currently no way to enable "Contacts to Multiple Accounts" in the scratch org configuration file: https://developer.salesforce.com/docs/atlas.en-us.sfdx_dev.meta/sfdx_dev/sfdx_dev_scratch_orgs_def_file_config_values.htm
Our repository/dx project includes the AccountContactRelation object and references it in layouts which means that this setting must be manually enable for every new scratch org before the source can be pushed to the scratch org. Because of this , we are not able to setup or CI pipeline to create temporary scratch orgs for testing.
Are there any workarounds for this? Also, is access to this setting in the config file planned to be released anytime soon?

A: Just a quick update: https://developer.salesforce.com/docs/atlas.en-us.sfdx_dev.meta/sfdx_dev/sfdx_dev_scratch_orgs_def_file_config_values.htm
It is now available.


text:
Q: Internal web scraper library Is there a python web scraper library that isn't a user-made or external library
I've found beautifulsoup, selenium, and requests as user-made libraries for python web scraping
before I start working on this I would just like to know if I do not need to install a different library

A: There is no web scraper library in the Python standard library.
There are http.client and html and other modules, which could be building blocks for a web scraping library... but at that point you're just doing by hand what Beautiful Soup and Requests do, so there's no point, really.


text:
Q: Using file_get_contents() on multiple remote image POST Am testing my luck with the MIT App Inventor, and am trying to POST more than 1 image at a time to my PHP script to insert in a database. I have successfully POSTed 1 image, but can't seem to do more than just 1 with file_get_contents. I have tried
$remote_content = explode("\n", file_get_contents('php://stdin'));
file_put_contents($upload_dir . $filename, $remote_content[0]); //etc

but all of the images have 0KB. Have also tried looping (foreach), to the same lack of success.
Is there some alternative? Or should this be POSTed differently on the app's side? Right now, it's individually posted all at 1 time (so
if not is empty image1,
 postFile image1
if not is empty image2
 postFile image 2

etc.


text:
Q: C++ передача указателя в функцию Есть функция с сигнатурой:
void some_func(Object &object);

Как единственный параметр, она принимает ссылку.
Создаем указатель:
Object *pObj = new Object();

Следующий шаг, логично напрашивается, что в верхнюю функцию мы должны передать ссылку, то есть:
some_func(&pObj);

Но компилятор этот вариант не принимает, а принимает такой:
some_func(*pObj);

Вопрос:
Как я понял ранее, оператор *, это оператор разыменования и если мы передаем *pObj, тогда передаем содержимое ссылки в функцию some_func.

*

*Почему вариант с указателями работает именно так?

*Почему мы не можем в метод с таким параметром передать ссылку? (&rObj)

*Что происходит при передаче some_func(*pObj)? По моим догадкам, создается копия объекта содержимого по ссылке указателя и потом передается как параметр в метод?

A: Оператор &something - это оператор получения адреса something. Поэтому когда вы пишете &pObj, а pObj - указатель, вы передаете адрес указателя, а функция у вас принимает адрес какой-то переменной. Оператор * разыменовывания указателя дает вам доступ к памяти, на которую указатель указывает, можно сказать, что вы как-будто получаете какую то переменную. И затем, при передаче в вашу функцию, ее тип неявно преобразуется к ссылке.
bar(int& u);

int obj;
int* pointer = &obj;
bar(*pointer); // => bar(obj)
bar(obj); // то, что вы хотели
bar(pointer); // функция принимает аргумент типа int, а не int*. Ошибка.
bar(&pointer); /* передаст адрес указателя,
    это подойдет, если bar принимает указатель на указатель: bar(int** u) */
bar(&obj); /* передаст адрес obj,
    это подойдет, если bar принимает указатель: bar(int* u) */

A: Токен &
В С++ этот токен имеет много значений:

*

*Как бинарный оператор - оператор побитового "и".
0b0011 & 0b0110; // 0b0010

*Как унарный оператор - оператор взятия адреса у переменной.
Type a;
Type * ap = & a; // указатель на переменную типа Type

*Как часть объвления типа - модификатора типа.
Type & r; // ссылка на переменную типа Type

Токен *
Этот токен имеет такой же набор значений

*

*Как бинарный оператор - оператор умножения.
3 * 5; // 15

*Как унарный оператор - оператор разыменовывания (взятие значения) переменной.
Type a;
Type & ar = * a; // ссылка на переменную типа Type

*Как часть объвления типа - модификатора типа.
Type * r; // указатель на переменную типа Type

Ссылки как значения
Работа с ссылками это как работа с их значениями.
Нельзя переопределить ссылку чтобы она указывала на другой объект.
Почти весь синтаксис для ссылки и для переменной значения одинаковый.
Ссылки обяъвляются как Type & name. И в дальнейшем ведут себя как обычные пермененые содержащие значение.
struct Type {
   int a;
}

Type o;
Type & r = o;

o.a = 1; // ok
r.a = 2; // ok

Переменную-ссылку можно присвоить обеъкту и наоборот:
Type & ref = o;
Type val;

ref = val;
val = ref;

Передача как аргумент функции тоже явлется присваиванием так что предыдущее верно и для них:
void fun1(Type x) {}
fun1(o); // ok
fun1(r); // ok

void fun2(Type & y) {}
fun2(o); // ok
fun2(r); // ok

Почему нельзя присвоить указатель ссылке.
Одна из наиболее важных причин для этого заключается в том, что указатель может содержать адрес не валидного объекта. Этот процесс отдан программистам:
void funcp(Type* p) {
    if (p == nullptr) {
        Type & r = &p; // Здесь ОС пошлет сигнал и программа аварийно завершится
    }
    else {
        Type & r = &p; // Здесь все должно быть хорошо
    }
}

Также указатель можно переназначить, но в случае передачи указателя в функцию это не имеет значения.
Есть еще ряд других случаев когда ссылки и указатели служат совсем разным целям, но это повод для отедльной статьи.

A: У вас 2 варианта. Либо использовать указатель, либо ссылку.
#include <iostream>

void some_func(int *obj){
    *obj = 6;
}

void some_func2(int &obj){
    obj = 5;
}

int main(){
    int obj;

    some_func(&obj);
    std::cout<<obj;//6

    some_func2(obj);
    std::cout<<obj;//5

    return 0;
}

&obj передаст указатель на объект, а не ссылку
Object *object = new Object();
//Создаётся указатель на новый объект
some_func(*object);
//* + (указатель на тип Object) = тип Object
//some_func принимает как аргумент объект, на который создаётся ссылка
//именно поэтому компилятор принимает такой вариант

A: Поскольку функция принимает ссылку на объект Object, вы должны передавать в эту функцию объект типа Object.
Если вы передаете в такую функцию указатель на объект, это считается несоответствием типа.
Если вы делаете так:
some_func(&pObj);

То, фактически, вы передаете адрес указателя на объект типа Object. То есть, вы передаете указатель на указатель на объект типа Object.
Выражение &pObj имеет тип Object **.


text:
Q: Programatically created RadioGroup OnClicked reading standard Android
Hi people below is my code what exactly I am doing is that I am trying to create radio group programmatically, which is done and my code is working fine for creating even for reading, but more I am concern about the standard how exactly we use to read on click of group, I feel at some point my code is taking too much of memory, I want to know that is there any other efficient good way to do this.

private void checkOnClickedRadioGroupCalled(ArrayList<LinearLayout> setRadioGroupValuesLinearLayoutList) {
        for (final LinearLayout group : setRadioGroupValuesLinearLayoutList) {
            String tag = group.getTag() + "_RadioGroup";
            System.out.println("Radio group tag name : - " + tag);
            final RadioGroup radioGroup = (RadioGroup) v.findViewWithTag(tag);
            if(radioGroup!=null) {
                radioGroup.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
                    RadioButton mButton1 = (RadioButton) radioGroup.getChildAt(0);
                    RadioButton mButton2 = (RadioButton) radioGroup.getChildAt(1);
                    //add this in constant
                    String idYes = group.getTag()+"Yes";
                    String idNo = group.getTag()+"No";
                    @Override
                    public void onCheckedChanged(RadioGroup group, int checkedId) {
                        System.out.println(" hascode of id getting as "+idYes.hashCode()+" And No " +idNo.hashCode());
                        if(mButton1.isChecked() && mButton1.getId() ==idYes.hashCode()) {
                            System.out.println(mButton1.getText() + "  :- Text of radio button");
                        } if(mButton2.isChecked()&& mButton2.getId()==idNo.hashCode()) {
                            System.out.println(mButton2.getText() + "  :- Text of radio button");

                        }
                    }

                });
            }
        }
    }


text:
Q: Why does $c$ in mean value theorem converge to $a$ and $b$, where $a < c < b$? In the context of proving integral rule (here), I'm very confused to why the following statement is true:

A form of the mean value theorem, $\int_a^b f(x)dx = (b-a)f(\xi)$
   where $a < \xi < b$, may be applied to the first and last integrals of
   the fomula for $\Delta \psi$ above, resulting in $$ \Delta \psi =
 -\Delta a f(\xi_1, \alpha + \Delta \alpha) + \int_a^b [f(x,\alpha + \Delta \alpha) - f(x,\alpha)] dx + \Delta b f(\xi_2, \alpha + \Delta
 \alpha)$$ Divide by $\Delta \alpha$ and let $\Delta \alpha \to 0$. Notice $\xi_1
 \to a$ and $\xi_2 \to b$.

It's the last part that is puzzling. Why do $\xi_1 \to a$ and $\xi_2 \to b$?

A: The $\xi_1$ is from the interval $(a,a+\Delta a)$ corresponding to an integral $\int_a^{a+\Delta a}$.
The mean value theorem is only applied on this small interval, not on $(a,b)$.
As $\Delta a\to0$, this interval shrinks and therefore $\xi_1\to a$.
Similarly, $\xi_2\in(b,b+\Delta b)$.
It might be that $\Delta a$ or $\Delta b$ is negative, but the proof works in that case as well with suitable reinterpretation.
In the calculation both $a$ and $b$ depend on $\alpha$ in a differentiable way.
The calculation (which is insufficiently explained in Wikipedia) we have $\Delta a=a(\alpha+\Delta\alpha)-a(\alpha)$.
Therefore $\Delta a\to0$ as $\Delta\alpha\to0$ and similarly for $b$.


text:
Q: Pole placement in uncontrollable systems with state-feedback. I am somewhat confused on how the standard form for an uncontrollable system can be used to implement state-feedback on the controllable subspace.

*

*I understand how to use feedback to achieve pole-placement in completely controllable systems.

*I don't understand how this can then be applied to controllable subspaces of uncontrollable systems.
For example, suppose I have an LTI system with eigenvalues {-1, ,1, 2} where eigenvalues {1, 2} are part of the controllable submatrix while -1 is uncontrollable. How do change the pole-locations for the controllable eigenvalues?
Thank you.

A: Since you only mentioned state feedback I assume that you are dealing with a system of the following form
$$
\dot{x} = A\,x + B\,u
$$
with $x \in \mathbb{R}^n$, $u \in \mathbb{R}^m$ and you want to find a state feedback $u = -K\,x$ such that the dynamics of the controllable parts of the system can be chosen. The entire state $x$ is considered to be known and thus observability does not have to be taken into consideration.
By looking at the controllable and uncontrollable states it is possible to find a similarity transformation which decomposes these states, similar to the Kalman decomposition but without also considering the observability. In order to do this you need the controllability matrix $\mathcal{C}$ defined as
$$
\mathcal{C} = \begin{bmatrix}
B & A\,B & \cdots & A^{n-1}B
\end{bmatrix}.
$$
A controllable decomposition can be found using the similarity transformation $T = \begin{bmatrix}T_1 & T_2\end{bmatrix}$, with the columns of $T_1$ having the same span as the controllability matrix and $T_2$ chosen such that $T$ is invertible. In the new coordinates, denoted by $x = T\,\hat{x}$, the dynamics are as follows
$$
\dot{\hat{x}} = \underbrace{T^{-1} A\,T}_{\hat{A}}\,\hat{x} + \underbrace{T^{-1} B}_{\hat{B}}\,u
$$
such that
$$
\hat{A} =
\begin{bmatrix}
A_{11} & A_{12} \\ 0 & A_{22}
\end{bmatrix}, \quad
\hat{B} =
\begin{bmatrix}
B_1 \\ 0
\end{bmatrix}
$$
where $A_{11}$ has the same size as the rank of $\mathcal{C}$ and the pair $(A_{11}, B_1)$ is controllable (their associated controllability matrix is full rank). So for this pair you can do pole placement, such that the poles of $A_{11}-B_1\,K_1$ can be chosen arbitrarily. Therefore, $u = -\begin{bmatrix}K_1 & 0\end{bmatrix} \hat{x}$ will place the controllable poles of $\hat{A}$ arbitrarily as well.
By using the definition of $\hat{x}$ it is possible to express this state feedback in terms of $x$ instead, namely $\hat{x} = T^{-1} x$. Or in other words your feedback gain can be found with $K = \begin{bmatrix}K_1 & 0\end{bmatrix}\,T^{-1}$.

For example given the system
$$
A =
\begin{bmatrix}
4 & 0 & 0 \\
-4 & 0 & -2 \\
-2 & -2 & 0
\end{bmatrix}, \quad
B =
\begin{bmatrix}
1 \\
0 \\
-1
\end{bmatrix},
$$
which has the eigenvalues $2$, $-2$ and $4$. This pair has the following controllability matrix
$$
\mathcal{C} =
\begin{bmatrix}
1 & 4 & 16 \\
0 & -2 & -12 \\
-1 & -2 & -4
\end{bmatrix},
$$
with has rank 2. It can be shown that its first two columns are linearly independent of each other, so an option for the similarity transformation would be
$$
T =
\begin{bmatrix}
1 & 2 & 0 \\
0 & -1 & 0 \\
-1 & -1 & 1
\end{bmatrix}.
$$
For the added last column it can be shown that it makes $T$ invertible (full rank). Performing the similarity transformation gives
$$
\hat{A} =
\begin{bmatrix}
0 & -4 & -4 \\
2 & 6 & 2 \\
0 & 0 & -2
\end{bmatrix}, \quad
\hat{B} =
\begin{bmatrix}
1 \\
0 \\
0
\end{bmatrix},
$$
such that
$$
A_{11} =
\begin{bmatrix}
0 & -4 \\
2 & 6
\end{bmatrix}, \quad
B_1 =
\begin{bmatrix}
1 \\
0
\end{bmatrix}.
$$
Finding a feedback gain for this pair, which places the poles at $-1$ and $-2$ gives $K_1 = \begin{bmatrix}9 & 24\end{bmatrix}$. So the actual state feedback gain can be calculated with
$$
K = \begin{bmatrix}K_1 & 0\end{bmatrix}\,T^{-1} =
\begin{bmatrix}9 & -6 & 0\end{bmatrix},
$$
which also places the two controllable poles of $A$, which are initially located at $2$ and $4$, at $-1$ and $-2$ respectively.


text:
Q: Where is the System maintenance switch on HP ProLiant dl360 Gen 7 I can not understand which is a possible switch, I could not even see pins. Please let me know if I am missing anything.

A: According to Document "HP ProLiant DL360 G7 Server Maintenance and Service Guide" (Fourth Edition) location of System Switch marked as 2
Item Number 2:


text:
Q: database design: link table for multiple different tables I have a conceptual question about database design which came up multiple times in my history as a developer.
Imagine I have a bigger database that is designed in the past, and already in production (for example you can take http://sqlfiddle.com/#!9/7c06f/1, a library database).
Now there is a new feature request: for every existing object in every table there shall be a "help text" (or something different, an error, a tag...) that you can all view in one place.
I implemented something like that multiple times in the past, but every time I'm not satisfied with the solution.
One solution is to have a link table with every table, like that:
CREATE TABLE BooksHelp (
    BookId  INT NOT NULL,
    HelpText VARCHAR NOT NULL
);

CREATE TABLE AuthorHelp (
    AuthorId  INT NOT NULL,
    HelpText VARCHAR NOT NULL
);

...

But I would need multiple link tables, which makes the selection of every existing "help text" difficult.
How would you design this problem? Is there another, better solution?

A: In the case of text items of some sort, especially if they are used in several tybles, like help texts, it seems preferable to centralize their text data in one table and store references in the tables that need them. This design also supports multi-lingual apps where the text items would have to be maintained in several languages.

A: This appears to be similar trying to map polymorphism to the relational model - it's just a bad fit - there's no obvious right answer.
There are a few obvious solutions. The one you've identified (storing the helptext in a linked table) is neat, but requires lots of joins if you're retrieving all the books for an author belonging to a publisher etc. As the business logic says "all objects should have helptext" (and I assume each row has different helptext), it's not super logical to store this in a child table - "helptext" is an attribute of each object, not a related concept.
You could also add a helptext column to each table. That stores the attribute in the main table, and reduces the cognitive load (as well as the number of joins). This is logical if each author, book, etc. has their own helptext.


text:
Q: How to remove default style of header in wordpress metabox I have the problem which when I create a header in my wordpress plugin metabox, it always apply the default style on my header:

even when I apply, my own style,
Text Block Settings
, it only changes the text color but not the background color, why??


text:
Q: how to avoid webGL shader loading putting too much load on cpu When loading up several hefty shader programs, webGl puts a lot of strain on the cpu, stalls the UI, and will sometimes even trigger chrome's cpu watchdog which kills the page.
What can I do to show a "loading" screen while this is going on and limit my processor usage so that I don't get ganked by chrome?
relevant section of code, which ultimately leads to these actual webGL calls:
var p = this.program = gl.createProgram();
gl.attachShader(p, this.makeShader(gl.VERTEX_SHADER, vertex));
gl.attachShader(p, this.makeShader(gl.FRAGMENT_SHADER, fragment));
gl.linkProgram(p);

A: A couple of ideas

*

*You can try to wait a few frames to check for results
var vs = gl.createShader(gl.VERTEX_SHADER);
gl.shaderSource(vs, vSource);
gl.compileShader(vs);
var fs = gl.createShader(gl.FRAGMENT_SHADER);
gl.shaderSource(fs, vSource);
gl.compileShader(fs);
var p = gl.createProgram();
gl.attachShader(p, vs);
gl.attachshader(p, fs);
gl.linkProgram(p);
gl.flush(); // Important!
setTimeout(checkResults, 2000);  // check results 2 seconds later

function checkResults() {
   var status = gl.getProgramParameter(p, gl.LINK_STATUS);
   ...
}

At least in Chrome this might mean the GPU process will compile the program while the Render process (The one running your JavaScript) will continue to run so at least JavaScript will not block unless of course if it's not finished by the time you check for results.

*Break stuff up into multiple steps
var tasks = [];

addTask(compileVertexShader);
addTask(compileFragmentShader);
addTask(linkProgram);
addTask(render);

function addTask(fn) {
  tasks.push(fn);
  runNextTask();
}

var taskRunning = false;
function runNextTask() {
  if (taskRunning) {
    return;
  }
  var taskFn = tasks.shift();
  if (taskFn) {
    taskRunning = true;
    setTimeout(function() {
      taskRunning = false;
      taskFn();
      runNextTask();
    }, 1);
  }
}

function compileVertexShader() {
  ...
}

function compileFragmentShader() {
  ...
}

function linkProgram() {
  ...
}

function render() {
  ...
}

As long as one function doesn't take too long there won't be any issues.
There are some common libraries for helping with this kind of stuff. For example the async library.


text:
Q: bash alias to create folder and move file I am trying to create a bash alias to do the following:

*

*create a folder (with the current date as the folder name)

*move (or copy, either is fine with me) a file from the current folder into the new folder.

The filename is passed to the alias as a variable. E.g., my-alias file.txt
Here are a few of the ways I've tried to go about it (although I've tried quite a few more variations):
alias my-alias="mkdir -v -p '$(date +%F)-List' && cp $1 './$(date +%F)-List/$1' && cd '$(date +%F)-List'"

alias my-alias="mkdir -v -p '$(date +%F)-List' && cp $1 ./$(date +%F)-List/$1 && cd '$(date +%F)-List'"

alias my-alias="mkdir -v -p '$(date +%F)-List' && cd '$(date +%F)-List' && cp ../$1 ./$1"

I've tried many ways of writing the command, and none work.
What am I over looking?
This is on Mac OS which should be the same as most other Linux environments.
UPDATE: WHERE I WENT WRONG
I've realised where I was getting confused. I have a lot of aliases set up that "appear" to receive arguments. I set them up a long time ago (some years ago). I now realise that the aliases only seem to receive the arguments because an alias can process whatever follows it when entered on command line. But it will only process those "arguments" if they are at the end of the command string the alias refers to, and in the same order.
So once I started trying to shuffle the arguments around in my aliases command string, the alias would break.
So yes, the best approach is to use a function.

A: If you must use alias, here's one that works by using -t to specify the destination directory before the actual argument for the file being moved:
alias my-alias="mkdir \$(date +%F); mv -t \$(date +%F)"

Works on Linux, I don't have a MacOS machine to test with though.

A: Use a function instead of an alias. This is pretty much always the answer if you run into trouble getting an alias to work. Especially if you're trying to use arguments (e.g. $1), since aliases don't really take arguments.
Also, you should pretty much always put double-quotes around parameter and variable references (i.e. "$1" instead of just $1). And don't run date multiple times, since it's possible (if improbable) you'll get different results; run it once and store the result in a variable. Try this:
my-function() {
    local subdir="$(date +%F)-List"
    mkdir -v -p "$subdir" &&
        cp "$1" "$subdir/$1" &&
        cd "$subdir"
}

A: As the answers to the other questions indicate: Aliases are just not good at handling parameters. You can even see that:
param=foo; do something with "$param"

That is how parameters work: First (both in time and in the command line) you set them, then you use them. In contrast to that:
<alias string with several commands to be expanded> <parameter>

The parameter can be a parameter to the last command in the alias. That is not what you need.
You can do this with an alias by building it as a single command from the shell's perspective but it is questionable whether that is a useful approach:
alias testalias='bash -c "echo \$1; echo \$1-" bash'
$ testalias foo
foo
foo-

One argument against it is that the quoting is complicated. Even I got that wrong first.

A: You need to create a function. mkdir -v -p '$(date +%F)-List' will only get evaluated at the time the alias was created


text:
Q: How to configure code formatters Beautify, Prettier, per project in VS Code Are there features that allow formatter configuration to be specific per project in VS Code? As in, I have one project I want indenting, and another project where I don't want indenting. I feel like I read somewhere that was possible, but I'm not finding it now that I'm searching for it.
I'm specifically using Beautify now because it has more configuration options.

A: Just use workspace settings, in VS Code you have User settings that are used for every project, and Workspace settings (saved in .vscode/settings.json in the project folder) that are specific to that project.
If you want to share workspace settings with others you can commit .vscode/settings.json.
You can edit both settings directly on the .json files, or through the VS Code settings editor (Files->Preferences->Settings).


text:
Q: Undefined method `user_path' in test Rspec I run test rspec and display error:
Failure/Error: before { visit user_path(user) }
   NoMethodError:
     undefined method `user_path' for #<RSpec::ExampleGroups::UserPages::ProfilePage:0xcd1f7c0>

How correct setting route for test?
user_spec.rb:
require 'rails_helper'

describe "User pages" do

  subject { page }

  describe "profile page" do
      let(:user) { FactoryGirl.create(:user) }
      before { visit user_path(user) }

      it { should have_content(user.name) }
      it { should have_title(user.name) }
  end
  describe "signup page" do
    before { visit signup_path }

    it { should have_content("Sign up") }
    it { should have_title(full_title('Sign up')) }
  end
end

My routes.rb, where added i route get '/users/:id', to: 'users#show', :as => :user
Rails.application.routes.draw do

  root 'static_pages#home'
  match '/help', to: 'static_pages#help', via: 'get'
  match '/about', to: 'static_pages#about', via: 'get'
  match '/contact', to: 'static_pages#contact', via: 'get'
  match '/signup', to: 'users#new', via: 'get'

  match '/signin', to: 'sessions#new', via: 'get'
  match '/signout', to: 'sessions#destroy', via: 'delete'
  get '/users/:id', to: 'users#show', :as => :user

  resources :users
  resources :sessions, only: [:new, :create, :destroy]

Explain me, please, how correct add route for test rspec. I use rails 4. M

A: I added type: :feature to describe "profile page" do and issue was fixed. Thank you,  BroiSatse!


text:
Q: How to update multiple record using checkbox in php? I would like to create an update for my table in php.
Here the design of my table:
Overtime Table
Then Here are the codes in displaying the table:
     <?php
        $db_host = 'localhost:3306'; // Server Name
        $db_user = 'root'; // Username
        $db_pass = ''; // Password
        $db_name = 'hrms'; // Database Name

        $conn = mysqli_connect($db_host, $db_user, $db_pass, $db_name);
        if (!$conn) {
          die ('Failed to connect to MySQL: ' . mysqli_connect_error());
        }
     ?>

Overtime Authorization

       <form method="GET" action="">
       Select Employee:
       <?php
          $sql ="SELECT `chapano`, concat(`Lname`,',',`fname`,`midname`) as
         `fullname` FROM `201` ORDER BY `fullname` ASC";
        $query = mysqli_query($conn, $sql);
         echo "<Select type='text' name='droplistsearch'>";
         while ($row=mysqli_fetch_array($query)) {
        echo"<option value='".$row['chapano']."'>".$row['chapano']." - "
        .$row['fullname']."</option>";
         }
       echo"</select>";
       ?>

      Date From:<input type="date" name="datefrom" id="datefrom">

        Date To:<input type="date" name="dateto" id="dateto">
        <input type="submit" name="submit" value="Submit">
     </form>

        Chapa No.
        Employee Name
        OT Date
         OT Time In
         OT Time Out
        Work Schedule
        Justification
        Status
        Total hours

    <form method="POST" action="overtime_addconn.php" id="OThours">
    <?php
     if(!empty($_GET['submit'])){
       $id = mysqli_real_escape_string($conn,$_REQUEST['droplistsearch']);
       $datefrom = mysqli_real_escape_string($conn,$_REQUEST['datefrom']);
       $dateto = mysqli_real_escape_string($conn,$_REQUEST['dateto']);

       $sql="SELECT `rowno`,`chapanoss`,`employee`,`date`,
      `ottimein`,`ottimeout`,`designation`,`remarks`,`ottotalhrs`,`status`
       FROM `overtimemulti`  WHERE `chapanoss` =  '$id' AND `date` BETWEEN
       '$datefrom' AND '$dateto' ";

       $result=mysqli_query($conn, $sql);
       $count =mysqli_num_rows($result);

       if($sql===FALSE) { die(mysql_error()); }
         while($row=mysqli_fetch_array($result)){
     ?>

      <input type="checkbox"  name="OTchekB" onClick="selectAll(this)" value="
      <?php echo $row['rowno'];?>">
      <input type="text" name="txOTchapa"  size="4px"  value="<?php echo
      $row['chapanoss'];?>" >
      <input type="text" name="txEmpName"  size="30px" value="<?php echo
      $row['employee'];?>" >
      <input type="Date" name="txOTDate"  value="<?php echo $row['date'];?>" >

      <input type="time" name="txTIMEIN3"  value="<?php echo
      $row['ottimein'];?>" >
      <input type="time" name="txTIMEOUT3"  value="<?php echo
      $row['ottimeout'];?>" >
      <input type="text" name="txSchedule"   size="3px" value="<?php echo
      $row['designation'];?>" >
      <input type="text" name="txJustify" value="<?php echo $row['remarks'];?
     >">

        <select name="txStatusOT" type="text">
          <option value="<?php echo $row['status'];?>">Aproved</option>
          <option value="Cancel">Cancel</option>
        </select>

      <input type="text" name="txTotalHrs" size="3" value="<?php $date =
        $row['date'];
        $From = $row['ottimein'];
        $To =  $row['ottimeout'];
        $starttime = new DateTime($date.''.$From);
        $endtime = new DateTime($date.''.$To);
        $diff = date_diff($starttime,$endtime);
        $totalhrs = $diff->h .'.'. $diff->i;
        echo $totalhrs;?>">

      <?php  } ?>

      <input type="submit" name="xOTsubmit" value="Submit" />
      <input type="submit" name="xOTUpdate" value="SAVE" />
     </form>
     <?php }mysqli_close($conn); ?>

Here my Code for Update:
}elseif(isset($_POST['xOTUpdate']))
{
    foreach(($_POST['OTchekB'] as $rowCount))
    {

        $chapano = $_POST['txOTchapa'];
        $employeename = $_POST['txEmpName'];
        $OTDate = $_POST['txOTDate'];
        $OTtimeIn = $_POST['txTIMEIN3'];
        $OTtimeOut = $_POST['txTIMEOUT3'];
        $Wrksched = $_POST['txSchedule'];
        $Remarks = $_POST['txJustify'];
        $OTtotalhrs = $_POST['txStatusOT'];
        $OTStatus = $_POST['txTotalHrs'];

        $sql2="UPDATE `overtimemulti` SET `date`= '$OTDate', `ottimein`='$OTtimeIn', `ottimeout`='$OTtimeOut',
        `designation`='$Wrksched', `remarks`='$Remarks', `ottotalhrs`='$OTtotalhrs',`status`= '$OTStatus' WHERE `rowno`='$rowCount' ";
        $result=mysqli_query($conn, $sql2);

    }
}

When trying to run this code I'm getting an error

Parse error: syntax error, unexpected 'as' (T_AS) in
  C:\xampp\htdocs\xampp\BISCOMHRMS\overtime_addconn.php on line 38

But still I don't know if my codes are correct or not.

A: Try below code, You have added two bracket  in foreach loop,
  foreach($_POST['OTchekB'] as $rowCount)
    {

        $chapano = $_POST['txOTchapa'];
        $employeename = $_POST['txEmpName'];
        $OTDate = $_POST['txOTDate'];
        $OTtimeIn = $_POST['txTIMEIN3'];
        $OTtimeOut = $_POST['txTIMEOUT3'];
        $Wrksched = $_POST['txSchedule'];
        $Remarks = $_POST['txJustify'];
        $OTtotalhrs = $_POST['txStatusOT'];
        $OTStatus = $_POST['txTotalHrs'];

        $sql2="UPDATE `overtimemulti` SET `date`= '$OTDate', `ottimein`='$OTtimeIn', `ottimeout`='$OTtimeOut',
        `designation`='$Wrksched', `remarks`='$Remarks', `ottotalhrs`='$OTtotalhrs',`status`= '$OTStatus' WHERE `rowno`='$rowCount' ";
        $result=mysqli_query($conn, $sql2);

    }


text:
Q: Synchronizing on a instance variable in a session scoped spring-bean to limit concurrent requests to a legacy service Due to a legacy system that doesn't handle multiple requests in parallell from the same user, I need to limit the amount of concurrent calls. The goal is to limit the number of concurrent requests to the service to 1 pr. user (session) - but not to have it block across all users. I could queue all ajaxrequests on the clientside, but that seems like a sledgehammer solution to a problem that only applies to certain calls. I'd like to solve this on the serverside if possible.
Alt. 1: possible problem might be that the autowired service is a proxy
(due to requestscope) injected by spring and that the injected proxy
reference might change across requests? Or does Spring reuse the same proxy - in which case it will work?
@Scope("session")
public class Model {
    @Autowired
    Service service;

    public List<Pojo> getPojos() {
        synchronized(service) {
            if(!hasTriedToRetrievePojos) {
                hasTriedToRetrievePojos = true;
                service.getPojos();
            }
        }
    }
}

@Scope("request")
// Actually a LegacyService, wrapping an old legacysystem
public class Service {
    ...
}

Alt. 2: if Spring only constructs one instance of this Model pr. session this should work as intended.
@Scope("session")
public class Model {
    private Object lock = new Object();

    @Autowired
    Service service;

    public List<Pojo> getPojos() {
        synchronized(lock) {
            if(!hasTriedToRetrievePojos) {
                hasTriedToRetrievePojos = true;
                service.getPojos();
            }
        }
    }
}

Alt. 3: inject the HttpSession in Model and manually synchronize on a HttpSession property (according to most upvoted answer in Is HttpSession thread safe, are set/get Attribute thread safe operations?). No spring confusion, but more cumbersome.
Given you use sticky sessions, I recon synchronization on session parameters should be safe even in a clustured environment?

A: I would favor your second solution, but doing a check before synchronizing (it's expensive) and another check in the synchronized block.
public List<Pojo> getPojos() {
     if (!hasTriedToRetrievePojos) {
         synchronized(lock) {
             if (!hasTriedToRetrievePojos) {
                 hasTriedToRetrievePojos = true;
                 service.getPojos();
             }
         }
     }
}

The service instance should be singleton as long as it doesn't contain any user/session relevant state at its instance level.
This solution has the advantage that the synchronization is encapsulated in Model only and does not rely on the correct configuration of Service (as in the first solution - e.g. @Scope("singleton") on the service would lead to a different behaviour). Besides that, first solution should work, too. Instead of @Scope("request") you could use @Scope("session").
If sticky sessions means a user's session is bound to one appserver instance and each of this user's requests gets directed to this instance, I would say yes, it is safe.


text:
Q: mod-rewrite with apache 2.4 and CentOs 7 don't replace index.php in url Have a Vagrantbox with centos 7 and apache 2.4. In /var/www/html have a Codeigniter PHP Site with pretty-url rewrite. I create the vm with puphpet config.yaml. The VM is running correct, VM-server is running correct, mode_rewrite ist activ and allowed to all, but i try a url like this:
http://codeigniter.dev/home ->file not found
http://codeigniter.dev/index.php/home -> site ok

There is no way to replace index.php, don't know why?
On my Server with Centos and apache this configrution runs perfect, but in my VM it didn't replace?!?
Here are my Configs:
puphpet/config.yaml
vagrantfile:
    target: local
    vm:
        provider:
            local:
                box: puphpet/centos7-x64
                box_url: puphpet/centos7-x64
                box_version: '0'
                chosen_virtualizer: virtualbox
                virtualizers:
                    virtualbox:
                        modifyvm:
                            natdnshostresolver1: false
                        showgui: 0
                    vmware:
                        numvcpus: 1
                    parallels:
                        linked_clone: 0
                        check_guest_tools: 0
                        update_guest_tools: 0
                machines:
                    vflm_via243h8nsof:
                        id: codeigniter
                        hostname: codeigniter.dev.local
                        network:
                            private_network: 192.168.56.101
                            forwarded_port:
                                vflmnfp_57zntu84qm8k:
                                    host: '9583'
                                    guest: '22'
                        memory: '2048'
                        cpus: '1'
        provision:
            puppet:
                manifests_path: puphpet/puppet/manifests
                module_path:
                    - puphpet/puppet/modules
                    - puphpet/puppet/manifests
                options:
                    - '--verbose'
                    - '--hiera_config /vagrant/puphpet/puppet/hiera.yaml'
        synced_folder:
            vflsf_f72ykqm374hd:
                source: ./
                target: /var/www
                sync_type: default
                smb:
                    smb_host: ''
                    smb_username: ''
                    smb_password: ''
                    mount_options:
                        dir_mode: '0775'
                        file_mode: '0664'
                rsync:
                    args:
                        - '--verbose'
                        - '--archive'
                        - '-z'
                    exclude:
                        - .vagrant/
                        - .git/
                    auto: 'true'
                owner: www-data
                group: www-data
        usable_port_range:
            start: 10200
            stop: 10500
        post_up_message: ''
    ssh:
        host: 'false'
        port: 'false'
        private_key_path: 'false'
        username: vagrant
        guest_port: 'false'
        keep_alive: '1'
        forward_agent: 'false'
        forward_x11: 'false'
        shell: 'bash -l'
        insert_key: 'false'
    vagrant:
        host: detect
    proxy:
        http: ''
        https: ''
        ftp: ''
        no_proxy: ''
server:
    install: '1'
    packages: {  }
users_groups:
    install: '1'
    groups:
        - www-data
    users:
        - www-data
locale:
    install: '1'
    settings:
        default_locale: de_DE.UTF-8
        locales:
            - en_GB.UTF-8
            - en_US.UTF-8
        timezone: Europe/Berlin
firewall:
    install: '1'
    rules: {  }
cron:
    install: '1'
    jobs: {  }
apache:
    install: '1'
    settings:
        version: 2.4
        user: www-data
        group: www-data
        default_vhost: true
        manage_user: false
        manage_group: false
        sendfile: 0
    modules:
        - proxy_fcgi
        - rewrite
    vhosts:
        av_myrx1sclhqnx:
            servername: codeigniter.dev
            serveraliases:
                - www.codeigniter.dev
            docroot: /var/www/html
            port: '80'
            setenv:
                - 'APP_ENV dev'
            setenvif:
                - 'Authorization "(.*)" HTTP_AUTHORIZATION=$1'
            custom_fragment: ''
            ssl: '0'
            ssl_cert: ''
            ssl_key: ''
            ssl_chain: ''
            ssl_certs_dir: ''
            ssl_protocol: ''
            ssl_cipher: ''
            directories:
                avd_6sroj6oyuexi:
                    path: /var/www/html
                    options:
                        - Indexes
                        - FollowSymlinks
                        - MultiViews
                    allow_override:
                        - All
                    require:
                        - 'all granted'
                    custom_fragment: ''
                    files_match:
                        avdfm_o1gz78z6saqx:
                            path: \.php$
                            sethandler: 'proxy:fcgi://127.0.0.1:9000'
                            custom_fragment: ''
                            provider: filesmatch
                    provider: directory
letsencrypt:
    install: '1'
    settings:
        email: admin@codeigniter.dev
    domains: {  }
php:
    install: '1'
    settings:
        version: '7.1'
    modules:
        php:
            - cli
            - intl
            - xml
        pear: {  }
        pecl: {  }
    ini:
        display_errors: 'On'
        error_reporting: '-1'
        session.save_path: /var/lib/php/session
        date.timezone: UTC
    fpm_ini:
        error_log: /var/log/php-fpm.log
    fpm_pools:
        phpfp_jncm5era33zg:
            ini:
                prefix: www
                listen: '127.0.0.1:9000'
                security.limit_extensions: .php
                user: www-user
                group: www-data
    composer: '1'
    composer_home: ''
ruby:
    install: '1'
    versions:
        rv_dpiw29f3bvhv:
            default: '1'
            bundler: '1'
            version: 2.3.1
            gems:
                - deep_merge@1.0.1
                - activesupport@4.2.6
                - vine@0.2
python:
    install: '1'
    packages: {  }
    versions: {  }
nodejs:
    install: '1'
    settings:
        version: '6'
    npm_packages: {  }
mysql:
    install: '1'
    settings:
        version: '5.7'
        root_password: '123'
        override_options: {  }
    adminer: 0
    users:
        mysqlnu_r5di0ad1ifk2:
            name: dbuser
            password: '123'
    databases:
        mysqlnd_k34jv21bgnjk:
            name: codeigniter
            sql: ''
    grants:
        mysqlng_rn6tn59qj8nf:
            user: dbuser
            table: '*.*'
            privileges:
                - ALL

.htaccess
RewriteEngine On
RewriteBase /
Options +FollowSymlinks
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(.*)$ index.php/$1 [L]

VM/ /etc/httpd/conf/httpd.conf
# Security
ServerTokens OS
ServerSignature On
TraceEnable On

ServerName "codeigniter.dev.local"
ServerRoot "/etc/httpd"
PidFile run/httpd.pid
Timeout 120
KeepAlive Off
MaxKeepAliveRequests 100
KeepAliveTimeout 15
LimitRequestFieldSize 8190

User www-data
Group www-data

<Directory /var/www/html>
Options Indexes FollowSymLinks MultiViews
  AllowOverride All
  Require all granted
</Directory>

HostnameLookups Off
ErrorLog "/var/log/httpd/error_log"
LogLevel warn
EnableSendfile Off

#Listen 80

Include "/etc/httpd/conf.modules.d/*.load"
Include "/etc/httpd/conf.modules.d/*.conf"
Include "/etc/httpd/conf/ports.conf"

LogFormat "%h %l %u %t \"%r\" %>s %b \"%{Referer}i\" \"%{User-Agent}i\"" combined
LogFormat "%h %l %u %t \"%r\" %>s %b" common
LogFormat "%{Referer}i -> %U" referer
LogFormat "%{User-agent}i" agent
LogFormat "%{X-Forwarded-For}i %l %u %t \"%r\" %s %b \"%{Referer}i\" \"%{User-agent}i\"" forwarded

I read a lot of posting for this problem, but no solution, so i hope to get some help here.


text:
Q: Is C++17 std::shared_mutex not available yet? Looking at C++ compiler support, it appears that the untimed version of std::shared_mutex is available in GCC 5.0+. However, even with gcc version 5.3.0 20151204 (Ubuntu 5.3.0-3ubuntu1~14.04), and compiling with -std=c++1z, a simple initialization of a shared mutex ends up with:
error: 'shared_mutex' in namespace 'std' does not name a type
        std::shared_mutex mutex_;

And no, I have already included the proper header: #include <shared_mutex>.
It can't locate the proper header, because it does not seem to exist. Actually, the linker uses the library locate at /usr/include/c++/5/shared_mutex, which contains only the implementation of the std::shared_timed_mutex (like the C++14 standard).
I have installed gcc-5 and g++-5 by adding the repository at ppa:ubuntu-toolchain-r/test and using update-alternatives to properly set up their bins.
Is there something I can do to compile my code correctly using the newest C++17 standard? And probably is a stupid question to ask, but is it too early to start using -std=c++1z even if it should be already supported? Because it is supported, right?

A: The confusion on cppreference was probably because std::shared_mutex really was added to GCC 5.0, in revision 200134. But that was the early incarnation of that type based on a C++1y draft. In fact it was the timed shared mutex, which was called  std::shared_mutex at the time.
Before the final C++14 standard was published std::shared_mutex was renamed to std::shared_timed_mutex, and so before the GCC 5.1 release (which is the first release in the 5.x series) the type in libstdc++ was renamed, see revision 207964.
So although at one point during the GCC 5.x pre-release phase there was a std::shared_mutex type, it wasn't the C++17 untimed one, and it got renamed before appearing in any official release of GCC.
Then, during the development of the GCC 6.x release series the C++1z untimed shared mutex got added, reusing the std::shared_mutex name. That's the commit T.C. linked to in the comments above, revision 224158.
So the C++17 untimed shared_mutex was never in any GCC 5.x version. For a brief period before the first 5.x release there was a timed one called std::shared_mutex, but in all proper 5.x releases it's called std::shared_timed_mutex.
The first release to ship the C++17 untimed one was 6.1 in April 2016, so with any GCC release after that you can use std::shared_mutex (as long as you enable C++17 in the compiler, e.g. with the -std=gnu++17 or -std=c++17 flag).
GCC 5 was released in 2015, so expecting to be able to use C++17 with that version is a bit unrealistic. GCC 6.x and 7.x have pretty good C++1z support (but only based on the current drafts at the time of release, of course).

A: follow this link to install/upgrade to the latest version of GCC and G++. http://tuxamito.com/wiki/index.php/Installing_newer_GCC_versions_in_Ubuntu
I have tried it on my ubuntu and successful.


text:
Q: getting a NoMethodError (undefined method `photo_url' for #): with rails and I can't find the solution I am trying to upload photos to my rails backend but I get the error mentioned above.
Here's the controller
class PhotosController < ApplicationController
  before_action :set_photo, only: [:show, :update, :destroy]

  # GET /photos
  def index
    @photos = Photo.where(drink_id: params[:drink_id])

    render json: @photos
  end

  # GET /photos/1
  def show
    render json: @photo
  end

  # POST /photos
  def create
    @photo = Photo.new(photo_params)

    if @photo.save
      render json: @photo, status: :created, location: @photo
    else
      render json: @photo.errors, status: :unprocessable_entity
    end
  end

  # PATCH/PUT /photos/1
  def update
    if @photo.update(photo_params)
      render json: @photo
    else
      render json: @photo.errors, status: :unprocessable_entity
    end
  end

  # DELETE /photos/1
  def destroy
    @photo.destroy
  end

  private
    # Use callbacks to share common setup or constraints between actions.
    def set_photo
      @photo = Photo.find(params[:id])
    end

    # Only allow a trusted parameter "white list" through.
    def photo_params
      params.require(:photo).permit(:name, :src, :drink_id)
    end
end

Here's the schema.rb
ActiveRecord::Schema.define(version: 2021_01_12_230812) do

  # These are extensions that must be enabled in order to support this database
  enable_extension "plpgsql"

  create_table "drinks", force: :cascade do |t|
    t.string "name"
    t.string "base"
    t.string "waves"
    t.text "description"
    t.string "shop"
    t.datetime "created_at", precision: 6, null: false
    t.datetime "updated_at", precision: 6, null: false
  end

  create_table "photos", force: :cascade do |t|
    t.string "name"
    t.text "src"
    t.bigint "drink_id", null: false
    t.datetime "created_at", precision: 6, null: false
    t.datetime "updated_at", precision: 6, null: false
    t.index ["drink_id"], name: "index_photos_on_drink_id"
  end

  add_foreign_key "photos", "drinks"
end

This is where I upload the photo
import React, { Component } from 'react'
import {getAllDrinks,uploadDrink, uploadPhoto } from './services/api-helper'
import './App.css';

class App extends Component {
  state = {
    allDrinks: null,
    drinkPhotos: null,
    formData: {

    }

  }

  async componentDidMount() {
    let allDrinks = await getAllDrinks();
    this.setState({
      allDrinks
    });
  }

  // lets user select image from their own files
  // sets state as the selected file
  // turns file into a readable url for src in an img tag
  fileChangedHandler = event => {
    let reader = new FileReader()
     reader.onload = (e) => {
       this.setState({ selectedFile: e.target.result})
     }
    reader.readAsDataURL(event.target.files[0])
    console.log(reader)
  }

    // sets state for formData based off of user input
    handleChange = (e) => {
      const { name, value } = e.target;
      this.setState(prevState => ({
        formData: {
          ...prevState.formData,
          [name]: value
        }
      }));
    }

     // adds this.state.selectedFile (users selected image) to this.state.formData
  // saves formData to the data base
 uploadHandler = () => {
   uploadDrink(this.state.formData)
   window.location.reload()
 }

  photoUploadHandler = () => {
    this.state.formData.src = `${this.state.selectedFile}`
    console.log(this.state.formData)
    uploadPhoto( this.state.formData.drink_id, this.state.formData)
    // window.location.reload()
  }

  render() {
    return (

        <input onChange={this.handleChange} placeholder='name' name='name'>
        </input>
      <input onChange={this.handleChange} placeholder='base' name='base'>
      </input>
      <input onChange={this.handleChange} placeholder='waves' name='waves'>
      </input>
      <input onChange={this.handleChange} placeholder='description' name='description'>
      </input>
      <input onChange={this.handleChange} placeholder='shop' name='shop'>
  </input>
        <button onClick={this.uploadHandler}>Upload!</button>

      <input type="file" onChange={this.fileChangedHandler} name='src'>
          </input>
      <input onChange={this.handleChange} placeholder='name' name='name'>
          </input>
          <input onChange={this.handleChange} placeholder='drink reference' name='drink_id'>
          </input>
        <button onClick={this.photoUploadHandler}>Upload!</button>

          {this.state.allDrinks ?
            this.state.allDrinks.map(drink=> (

{drink.name }

            ))
            :
            <></>
        }

    );
  }

}

export default App;

I've been racking my brain for days now and can't figure out where the error comes from, any help will be appreciated.


text:
Q: Magento crob job 404 not found page when executing from browser I have two Magento installations, one is my primary store and other for testing, I have an installation on a subdomain: mystore.mydomain.com this is for testing, when I go to the browser to: mystore.mydomain.com/cron.php it returns a 404 error, in my primary installation mydomain.com/cron.php returns a blank page and queue newsletters start sending, cron.php is indeed located at the root of mystore.mydomain.com, I also did mystore.mydomain.com/magento-cleanup.php and the path works, so the problem is not the path. What is the problem?

A: Please check below two things.
1. cron.php file is exists in the root of magento.
2. Its not disable by htaccess. We can disable cron.php by htaccess.


text:
Q: Generate distinct values from a column in a spark dataframe I have a spark dataframe like below
id|name|age|sub
1 |ravi|21 |[M,J,J,K]

I don't want to explode on the column "sub" as it will create another extra set of rows. I want generate unique values from the "sub" column and assign it to new column sub_unique.
My output should be like
id|name|age|sub_unique
1 |ravi|21 |[M,J,K]

A: You can use udf
val distinct = udf((x: Seq[String]) => if (s != null) x.distinct else Seq[String]())

df.withColumn("subm_unique", distinct($"sub"))


text:
Q: building docker image throws gyp ERR! not ok when installing npm I've built a vue.js application and wanted to create an image using docker. However, I get several gyp ERR! lines when I run the docker build command. I have no problem running the app on my machine using the npm run serve command.
#10 49.03 npm ERR! code 1
#10 49.03 npm ERR! path /app/node_modules/node-sass
#10 49.03 npm ERR! command failed
#10 49.03 npm ERR! command sh -c node scripts/build.js
#10 49.03 npm ERR! Building: /usr/local/bin/node /app/node_modules/node-gyp/bin/node-gyp.js rebuild --verbose --libsass_ext= --libsass_cflags= --libsass_ldflags= --libsass_library=
#10 49.03 npm ERR! gyp info it worked if it ends with ok
#10 49.03 npm ERR! gyp verb cli [
#10 49.03 npm ERR! gyp verb cli   '/usr/local/bin/node',
#10 49.03 npm ERR! gyp verb cli   '/app/node_modules/node-gyp/bin/node-gyp.js',
#10 49.03 npm ERR! gyp verb cli   'rebuild',
#10 49.03 npm ERR! gyp verb cli   '--verbose',
#10 49.03 npm ERR! gyp verb cli   '--libsass_ext=',
#10 49.03 npm ERR! gyp verb cli   '--libsass_cflags=',
#10 49.03 npm ERR! gyp verb cli   '--libsass_ldflags=',
#10 49.03 npm ERR! gyp verb cli   '--libsass_library='
#10 49.03 npm ERR! gyp verb cli ]
#10 49.03 npm ERR! gyp info using node-gyp@3.8.0
#10 49.03 npm ERR! gyp info using node@16.13.1 | linux | x64
#10 49.03 npm ERR! gyp verb command rebuild []
#10 49.03 npm ERR! gyp verb command clean []
#10 49.03 npm ERR! gyp verb clean removing "build" directory
#10 49.03 npm ERR! gyp verb command configure []
#10 49.03 npm ERR! gyp verb check python checking for Python executable "python2" in the PATH
#10 49.03 npm ERR! gyp verb `which` failed Error: not found: python2
#10 49.03 npm ERR! gyp verb `which` failed     at getNotFoundError (/app/node_modules/which/which.js:13:12)
#10 49.03 npm ERR! gyp verb `which` failed     at F (/app/node_modules/which/which.js:68:19)
#10 49.03 npm ERR! gyp verb `which` failed     at E (/app/node_modules/which/which.js:80:29)
#10 49.03 npm ERR! gyp verb `which` failed     at /app/node_modules/which/which.js:89:16
#10 49.03 npm ERR! gyp verb `which` failed     at /app/node_modules/isexe/index.js:42:5
#10 49.03 npm ERR! gyp verb `which` failed     at /app/node_modules/isexe/mode.js:8:5
#10 49.04 npm ERR! gyp verb `which` failed     at FSReqCallback.oncomplete (node:fs:198:21)
#10 49.04 npm ERR! gyp verb `which` failed  python2 Error: not found: python2
#10 49.04 npm ERR! gyp verb `which` failed     at getNotFoundError (/app/node_modules/which/which.js:13:12)
#10 49.04 npm ERR! gyp verb `which` failed     at F (/app/node_modules/which/which.js:68:19)
#10 49.04 npm ERR! gyp verb `which` failed     at E (/app/node_modules/which/which.js:80:29)
#10 49.04 npm ERR! gyp verb `which` failed     at /app/node_modules/which/which.js:89:16
#10 49.04 npm ERR! gyp verb `which` failed     at /app/node_modules/isexe/index.js:42:5
#10 49.04 npm ERR! gyp verb `which` failed     at /app/node_modules/isexe/mode.js:8:5
#10 49.04 npm ERR! gyp verb `which` failed     at FSReqCallback.oncomplete (node:fs:198:21) {
#10 49.04 npm ERR! gyp verb `which` failed   code: 'ENOENT'
#10 49.04 npm ERR! gyp verb `which` failed }
#10 49.04 npm ERR! gyp verb check python checking for Python executable "python" in the PATH
#10 49.04 npm ERR! gyp verb `which` failed Error: not found: python
#10 49.04 npm ERR! gyp verb `which` failed     at getNotFoundError (/app/node_modules/which/which.js:13:12)
#10 49.04 npm ERR! gyp verb `which` failed     at F (/app/node_modules/which/which.js:68:19)
#10 49.04 npm ERR! gyp verb `which` failed     at E (/app/node_modules/which/which.js:80:29)
#10 49.04 npm ERR! gyp verb `which` failed     at /app/node_modules/which/which.js:89:16
#10 49.04 npm ERR! gyp verb `which` failed     at /app/node_modules/isexe/index.js:42:5
#10 49.04 npm ERR! gyp verb `which` failed     at /app/node_modules/isexe/mode.js:8:5
#10 49.04 npm ERR! gyp verb `which` failed     at FSReqCallback.oncomplete (node:fs:198:21)
#10 49.04 npm ERR! gyp verb `which` failed  python Error: not found: python
#10 49.04 npm ERR! gyp verb `which` failed     at getNotFoundError (/app/node_modules/which/which.js:13:12)
#10 49.04 npm ERR! gyp verb `which` failed     at F (/app/node_modules/which/which.js:68:19)
#10 49.04 npm ERR! gyp verb `which` failed     at E (/app/node_modules/which/which.js:80:29)
#10 49.04 npm ERR! gyp verb `which` failed     at /app/node_modules/which/which.js:89:16
#10 49.04 npm ERR! gyp verb `which` failed     at /app/node_modules/isexe/index.js:42:5
#10 49.04 npm ERR! gyp verb `which` failed     at /app/node_modules/isexe/mode.js:8:5
#10 49.04 npm ERR! gyp verb `which` failed     at FSReqCallback.oncomplete (node:fs:198:21) {
#10 49.04 npm ERR! gyp verb `which` failed   code: 'ENOENT'
#10 49.04 npm ERR! gyp verb `which` failed }
#10 49.04 npm ERR! gyp ERR! configure error
#10 49.04 npm ERR! gyp ERR! stack Error: Can't find Python executable "python", you can set the PYTHON env variable.
#10 49.04 npm ERR! gyp ERR! stack     at PythonFinder.failNoPython (/app/node_modules/node-gyp/lib/configure.js:484:19)
#10 49.04 npm ERR! gyp ERR! stack     at PythonFinder.<anonymous> (/app/node_modules/node-gyp/lib/configure.js:406:16)
#10 49.04 npm ERR! gyp ERR! stack     at F (/app/node_modules/which/which.js:68:16)
#10 49.04 npm ERR! gyp ERR! stack     at E (/app/node_modules/which/which.js:80:29)
#10 49.04 npm ERR! gyp ERR! stack     at /app/node_modules/which/which.js:89:16
#10 49.04 npm ERR! gyp ERR! stack     at /app/node_modules/isexe/index.js:42:5
#10 49.04 npm ERR! gyp ERR! stack     at /app/node_modules/isexe/mode.js:8:5
#10 49.04 npm ERR! gyp ERR! stack     at FSReqCallback.oncomplete (node:fs:198:21)
#10 49.04 npm ERR! gyp ERR! System Linux 5.10.60.1-microsoft-standard-WSL2
#10 49.04 npm ERR! gyp ERR! command "/usr/local/bin/node" "/app/node_modules/node-gyp/bin/node-gyp.js" "rebuild" "--verbose" "--libsass_ext=" "--libsass_cflags=" "--libsass_ldflags=" "--libsass_library="
#10 49.04 npm ERR! gyp ERR! cwd /app/node_modules/node-sass
#10 49.04 npm ERR! gyp ERR! node -v v16.13.1
#10 49.04 npm ERR! gyp ERR! node-gyp -v v3.8.0
#10 49.04 npm ERR! gyp ERR! not ok
#10 49.04 npm ERR! Build failed with error code: 1
#10 49.27
#10 49.27 npm ERR! A complete log of this run can be found in:
#10 49.27 npm ERR!     /root/.npm/_logs/2021-12-26T11_47_39_634Z-debug.log
------

executor failed running [/bin/sh -c npm install]: exit code: 1

It seems that node-sass is the culprit but I can't understand how I can solve this issue without removing it as my project depends on it.
Dockerfile:
# Choose the Image which has Node installed already
FROM node:lts-alpine

# install simple http server for serving static content
RUN npm install -g http-server

# make the 'app' folder the current working directory
WORKDIR /app

# copy both 'package.json' and 'package-lock.json' (if available)
COPY package*.json ./

# install project dependencies
RUN npm install

# copy project files and folders to the current working directory (i.e. 'app' folder)
COPY . .

# build app for production with minification
RUN npm run build

EXPOSE 8081
CMD [ "http-server", "dist" ]

package.json file:
{
  "name": "vue-argon-design-system",
  "version": "0.1.0",
  "private": true,
  "scripts": {
    "serve": "vue-cli-service serve",
    "build": "vue-cli-service build",
    "lint": "vue-cli-service lint"
  },
  "dependencies": {
    "axios": "^0.24.0",
    "bootstrap-vue": "^2.0.4",
    "flatpickr": "^4.5.1",
    "nouislider": "^11.1.0",
    "register-service-worker": "^1.5.2",
    "sweetalert2": "^11.3.0",
    "vue": "^2.6.6",
    "vue-flatpickr-component": "^8.1.1",
    "vue-lazyload": "^1.2.6",
    "vue-multiselect": "^2.1.6",
    "vue-router": "^3.0.2",
    "vue2-datepicker": "^3.10.4",
    "vue2-transitions": "^0.2.3"

  },
  "devDependencies": {
    "@vue/cli-plugin-babel": "^3.4.0",
    "@vue/cli-plugin-eslint": "^3.4.0",
    "@vue/cli-plugin-pwa": "^3.4.0",
    "@vue/cli-service": "^3.4.0",
    "node-sass": "^4.11.0",
    "sass-loader": "^7.1.0",
    "vue-template-compiler": "^2.6.6"
  }
}

A: As AAber has pointed out the problem was about python and not node.js. The base image could not run python. Updating the image to node:12.14-alpine solved it. Many thanks.


text:
Q: Error establishing a database connection - wordpress I get this error. The connection details in the wp-config file are correct. I have only been getting this error ever since I sent the website files to my boss to put the website online. I also did a dump of the database to send to him.
Is it at all possible that something he did effected my local copy of the wordpress website? It doesn't seem so...but I have only had this issue since he put it online. Maybe did I remove my database by mistake when I did the dump? Can I check that somehow?
Does a database dump mess up my database? I was the one that did the database dump, to send to him. Did it move my database?
Can I reinstall wordpress as a solution and copy my website into it?
Cheers.

A: Check if your live server database credentials match with details in your wp-config.
your localohost credential might be different from server credential
Secondly check if your boss has restored dump database


text:
Q: Difference between version number, minor number and release number I'm reading http://www.tldp.org/HOWTO/Program-Library-HOWTO/shared-libraries.html and I had some questions.
What is difference between version, minor and release number? What is meant by the part "version number is incremented whenever the interface changes"?

The soname has the prefix lib, the name of the library, the phrase .so, followed by a period and a version number that is incremented whenever the interface changes.
The real name adds to the soname a period, a minor number, another period, and the release number.

A: Each time you release the library, it should arguably have a different version number.  However, some releases only make changes to the internal workings of the library without affecting users at all other than by fixing bugs.  Other releases may also add new functions to the library, but the interface details of all the existing functions are the same as before, so software written to use an older version of the library will continue to work with the new version.  Other changes may break backwards compatibility; a function interface changes, a structure changes size, or a function is dropped (or a global variable — perish the thought — changes, etc).
The 'bug fix only' versions might not bother with renumbering the library, but if you previously had liberror.so.1.0.2, the new version might be liberror.so.1.0.3, a change in the release number.
The 'additional features' versions should be given a new minor number, so the new version after liberror.so.1.0.2 might be liberror.so.1.1.0.
If you break compatibility, then you use a new version number, so the new version after liberror.so.1.0.2 might be liberror.so.2.0.0.
Code built to use liberror.so.1.0.2 can and will use either liberror.so.1.0.3 or liberror-1.1.0 without problem, but will not attempt to use liberror.so.2.0.0 or later versions.

What code (in a GNU binutils stack, for example) controls which versions will be linked to, and is this behavior fixed or overridable?

Good question.  This is my understanding, but I might have some details wrong (in which case, someone will probably point out the error of my ways).  The theory above is nice an easy; this is a little less easy.
You may have noticed that there are 'development' packages for libraries as well as the 'standard' versions of the libraries.  The difference between them is part of the explanation.
If you're an ordinary end user who is not writing programs using a library but simply running programs that someone else has written, then you typically end up with one file and one symlink in the installation directory.  Continuing with the hypothetical liberror.so.1.0.2 example (installed in /usr/local/lib), you would find in the base release:
liberror.so.1.0.2   — the real shared object
liberror.so.1       — symlink to the the real shared object

If you installed the development version, you'd probably find some header files in /usr/local/include, some man pages (perhaps in /usr/local/man, perhaps in /usr/share instead), and an extra symlink:
liberror.so         — another symlink, either to liberror.so.1 or to liberror.so.1.0.2

When the program using it is compiled, you might specify:
gcc -I/usr/local/include usererror.c -o usererror -L/usr/local/lib -lerror

This will link with the name liberror.so, but reading the metadata from the liberror.so.1.0.2 file, it would know that the version to use is liberror.so.1.0.2 or later (but not liberror.so.2.0.0 or later).
Now let's suppose you upgrade the installation to liberror.so.2.0.0.  You now have files:
liberror.so.1.0.2   — the real shared object
liberror.so.1       — symlink to the the real shared object
liberror.so.2.0.0   — the real shared object
liberror.so.2       — symlink to the the real shared object
liberror.so         — another symlink, either to liberror.so.2 or to liberror.so.2.0.0

Old code built to use liberror.so.1 still runs using that library.  New code built to use liberror.so.2 also runs using the new library.  And at link time, new programs pick up liberror.so.2.0.0 via the symlink liberror.so.
You can control it so that the default on your system is still liberror.so.1 by adjusting the liberror.so symlink to point to liberror.so.1.0.2.  The only tricky part is making sure that the correct versions of the headers are available for compilation.  It is a bad idea to build with the headers for liberror.so.2 and link with liberror.so.1 because the one thing you know for sure is that the interfaces are different!

Some raw data from a Red Hat Enterprise Linux 5 (RHEL5) x86_64 machine.
$ cd /lib64
$ ls libc*
-rwxr-xr-x 1 root root 1713088 2009-01-05 16:32 libc-2.5.so
lrwxrwxrwx 1 root root      11 2012-02-22 15:05 libcap.so -> libcap.so.1
lrwxrwxrwx 1 root root      14 2012-02-22 15:05 libcap.so.1 -> libcap.so.1.10
-rwxr-xr-x 1 root root   17384 2006-11-14 01:36 libcap.so.1.10
-rwxr-xr-x 1 root root  197744 2009-01-05 16:32 libcidn-2.5.so
lrwxrwxrwx 1 root root      14 2012-02-22 15:05 libcidn.so.1 -> libcidn-2.5.so
lrwxrwxrwx 1 root root      17 2012-02-22 15:05 libcom_err.so.2 -> libcom_err.so.2.1
-rwxr-xr-x 1 root root   10000 2008-09-30 13:27 libcom_err.so.2.1
-rwxr-xr-x 1 root root   48600 2009-01-05 16:32 libcrypt-2.5.so
-rwxr-xr-x 1 root root 1048728 2005-10-31 06:47 libcrypto.so.0.9.6b
-rwxr-xr-x 1 root root 1365504 2008-12-16 08:09 libcrypto.so.0.9.8e
lrwxrwxrwx 1 root root      19 2012-02-22 15:05 libcrypto.so.2 -> libcrypto.so.0.9.6b
lrwxrwxrwx 1 root root      19 2012-02-22 15:05 libcrypto.so.4 -> libcrypto.so.0.9.8e
lrwxrwxrwx 1 root root      19 2012-02-22 15:05 libcrypto.so.6 -> libcrypto.so.0.9.8e
lrwxrwxrwx 1 root root      15 2012-02-22 15:05 libcrypt.so.1 -> libcrypt-2.5.so
lrwxrwxrwx 1 root root      11 2012-02-22 15:05 libc.so.6 -> libc-2.5.so
$

You can see the libc.so.6 is a symlink to libc-2.5.so.  You can also a number of versions of libcrypto, not including the link-time library libcrypto.so.  You can also see libraries with only two parts to the version number, etc.  The represented libraries are libc, libcap, libcidn, libcom_err, libcrypt and libcrypto.


text:
Q: selecting specfic options within a dropdown list with jquery I'd like to be able to select a specific option within a dropdown list in order to manipulate it.
For example,
$("#mylist > option14").replaceWith(<option value="option155">New Option</option>

How can I do this?
Selecting through the child selector doens't seem to work.
Thanks.

A: $("#mylist option").each(function(){
  if($(this).val() == "option14"){
    $(this).replaceWith('<option value="option155">New Option</option>');
  }
});

or
$("#mylist option[value=option14]").replaceWith(
  '<option value="option155">New Option</option>'
);

A: You can do with :
$("select#mylist option[value='option14']").replaceWith('<option value="option155">New Option</option>');

Try below example:
<html>
<head id="Head1" runat="server">

    <script language="javascript" type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.min.js"></script>
    <title></title>
    <script type="text/javascript">
        $(function()
        {
            $("select#mylist option[value='option14']").replaceWith('<option value="option155">New Option</option>');
        });

    </script>
</head>
<body>
    <select id="mylist">
        <option value="option11">One</option>
        <option value="option12">Two</option>
        <option value="option13">Three</option>
        <option value="option14">Four</option>
    </select>
</body>
</html>


text:
Q: Convert checklist into dropdown Here is the checklist radio button code I am using right now, I would like to convert it into a dropdown and allow to select only one option at a time.
Someone give me an example on how to do this ?
I tried but couldn't get a working result, this is the last feature I need to make my filter functions complete.
Example image attached

Sort

<input type="radio" id="radio" class="common_selector sort" name="radio" value="ASC"> ASC

<input type="radio" class="common_selector sort" name="radio" value="DESC" > DESC

The following JQuery function is capturing data from this checklist

Already tried the following and it is not doing anything.
<select name="dropdown" size=1>
    <option class="common_selector sort" value="DESC">option 1</option>
    <option class="common_selector sort" value="ASC">option 2</option>
</select>

A: You need to connect the select box to the jQuery, e.g. by adding the class attribute.
<select name="dropdown" size=1 class="common_selector">
    <option class="common_selector sort" value="DESC">option 1</option>
    <option class="common_selector sort" value="ASC">option 2</option>
</select>

Change the jQuery for a select element
$('.common_selector').change(function() {
    filter_data();
});

-it would be odd to 'convert' radiobuttons to a select.


text:
Q: jQuery - Change href attr I trying to change href via jQuery, but I don't know why it's not working...
$(document).ready(function () {
  var oldurl = $('`http://google.com`');
  var newurl = $('`http://yahoo.com`');

  $('a[href="' + oldurl + '"]').attr('href', newurl);

  // it's not working too...
  //$('a[href="http://google.com"]').attr('href', 'http://yahoo.com');

  // it's not working too...
  //$('.mylink').attr('href', newurl);
});

JSFiddle

A: You just need:
var oldurl = 'http://google.com';
var newurl = 'http://yahoo.com';
$('a[href="' + oldurl + '"]').attr('href', newurl);

Demo
Urls must be string and not jQuery objects and you forgot to close the square bracket.