text:
Q: What is the origin of the exclamation mark? Granted this applies to more than English, but I hope it's not off topic.
Recently I wondered when the exclamation point/mark entered our language and how. I did search the site for an answer and didn't find one.
With Googling, I accumulated a lot of interesting tidbits (below), but no good answer. The most repeated story follows.
Smithsonian.com posits that ! has it's origin in the Latin exclamation of joy, io, where the i was written over the o.
I was pretty surprised by this, as I have never seen it that way (given, I don't have a lot of Latin manuscripts hanging around.) They did state, though, that:

...it wasn't until 1970 that the exclamation point had its own key on the keyboard. Before that, you had to type a period, and then use the backspace to go back and stick an apostrophe above it.*

Wikipedia gives the same origin as Smithsonian.com with a touch more detail:

The modern graphical representation is believed to have been born in the Middle Ages. The Medieval copyists used to write at the end of a sentence the Latin word io to indicate joy. The word io meant hurray. Along time, the i moved above the o, and the o became smaller, becoming a point.

The sources of the above are not easy to access.
Sentence First gave a colorful account of the various names for the exclamation mark, beginning with Ben Johnson's term for it: admiration mark, but, sadly, no history.
The American Bookmaker, A Journal of Technical Art and Information states in the May, 1888 edition:

The popular notion has always been that… the exclamation point (!) owes its existence to the Latin word Io (joy)… This explanation of the origin… is ingenious and one might almost say picturesque. For it, the world is indebted to one Willem Bilderdijk, a Dutch poet and philologist, born at Amsterdam in 1756. This entirely fanciful exegesis… goes to show that, with true poetic insight, Bilderdijk looked to his imagination rather than to scientific investigation for his facts.

I'm inclined to believe the above. Again, however, no actual history is given.
Interestingly, in an unrelated entry about dropped caps, a blogger posts an image of an illuminated manuscript that has what might possibly be interpreted as exclamation points (e.g. see Col. 1, third line from the bottom.)

However, above that, the same mark is found where there is a question in the Latin Vulgate (starting line 8 from the bottom):

Infirmatur quis in vobis (strange mark) inducat presbyteros ecclesiae et orent super eum unguentes eum oleo in nomine Domini: et oratio fidei salvabit infirmum (and here again the strange mark) et adlevabit eum Dominus et si in peccatis sit dimittentur ei...

Translated:

Is any man sick among you? Let him bring in the priests of the church and let them pray over him, anointing him with oil in the name of the Lord. And the prayer of faith shall save the sick man . (<- Note, no question.) And the Lord shall raise him up...

And even further up:

ecce beatificamus qui sustinuerunt sufferentiam Iob audistis (strange mark) et finem Domini...

Which translates to:

Behold, we account them blessed who have endured. You [have heard of the patience of] Job (strange mark, translation not exact because the syntax is a bit different) and you have seen the end of the Lord...

So, I am no closer to the answer than I was when I began.
Any help would be appreciated.
I actually remember doing this on my dad's Smith-Corona. :(
NYT opinion writer Ben Yagota wrote, "A friend's 12-year-old daughter once said that in her view, a single exclamation point is fine, as is three, but never two. My friend asked her where this rule came from and the girl said, 'Nowhere. It's just something you learn.'" Two exclamation marks look strange to me, too.

"They were apparently also casually known by the names shriekmark, screamer, bang, pling, smash, soldier, and control (via About.com); gasper, startler, and dog's cock (from Lynne Truss's Eats, Shoots & Leaves); the more alliterative dog's dick; and slammer. Plausible but unverified names include ball-bat, boing, dembanger, eureka, screech, shout pole, smash, spark-spot, and wham."

A: I tried to translate the French wikipedia article:

The origin of exclamation mark is uncertain. According to one theory,
  this symbol comes from the joy exclamation, "io" in Latin, abbreviated
  with a "i" above an "o".
Another theory states that it finds its origine in musical notation.
Around 1360, Iacopo Alpoleio da Urbisaglia, who wrote Ars punctuandi
  (the Art of punctuating) claims to be the inventor of the exclamation
  point, which he called "admiration point". It consisted of two points
  with an oblique line above them, tilted to the right - a combination
  resembling the "scandicus", a musical notation element (neume) used
  to mark ascending notes, before the 5 lines notation was invented.
The first known "admiration point" is to be found in De nobilitate
  legum et medicine, by Coluccio Salutati in 1399.
The exclamation mark shape was finalized with the development of
  printing. It is found in the 14th century in the "Mayence psalter" by
  Peter Schöffer and Johannes Fust publshed in 1457.
In France, it is found with other recent signs of punctuation in
  "Roman" font - Freiburger , Gering and Kranz (Paris 1470), Michel
  Toulouse Michel (Paris, 1472).
It appears nearly 50 years later in the Grammatografia
  of Jacques Lefevre d'Etaples published by Simon de Colines in 1529,
  and in the 16th century in works of Rabelais and Marot published by
  Étienne Dolet.

A: I found a very insightful excerpt from the book, Spinoza's Ethica from Manuscript to Print: Studies on Text, Form and Related Topics
(Link takes you to page with excerpt).

The exclamation mark (punctus exclamativus or admiratlvus) is thought to have originated in humanistic circles in the latter half of the fourteenth century. According to Parkes (1992, 49), its invention has been claimed by Iacopo Alpoleio da Urbisaglia. It is, however, unclear who was the author of an Ars punctandi in which the exclamation mark was first proposed; see Ullman
  1963. 35,111. It has been attributed, wrongly, to Petrarca; Ullman takes Coluccio Salutati to be its author.  The earliest instance of the exclamation mark is to be found in a manuscript by Salutati from 1399; Parkes 1992, pl. 30, reproduces a page from this manuscript. For references to this new sign by some grammarians (including Aldus), see Greidanus 1926, 212, 216-8, 222."

I found an image that contains a piece of the manuscript which is believed to be the first instance of the exclamation point. The image also offers an evolution of the mark:

Coluccio Salutati, De nobilitate legum and medicine, 1399 (BNF). First use of an exclamation mark (before the last word). Historian Malcolm B. Parkes, Salutati revised itself punctuation of this manuscript.
     |  Translated from French SOURCE

I also found some other good sources. This comes from a web article, here
and cites a book called On the Dot (preview available)

"…the exclamation point … is derived either from an abbreviation of Latin interiectiō (interjection) or from the Latin interjection Iō! ('Hey!')." In their most recent book, On the Dot, the Brothers Humez explain that the exclamation mark was known in English as "note or mark of admiration (a straight-forward translation of Iacopo's term punctus admirativus)," and the term "exclamation point" was adopted in the 17th century. [...] Medieval scribes stacked the i above the o, the o became a point, and thus evolved this energetic punctuation mark.

Tl;dr: The exclamation point originated sometime between 1300s-1400s in humanistic circles, Lacopo Alpoleio da Urbisaglia has claimed inventing it, however Berthold Ullman credits Coluccio Salutati, and the earliest instance of the mark comes from a manuscript by Salutati from 1399. Comes from the latin interjection, "Iō" and scribes stacked the 'i' over the 'o'. It was originally called the "mark of admiration" in English and wasn't called an "exclamation point" until the 17th century.

A: I hesitate to take this topic even farther afield, yet getting at the origin may take it there.
An unsupported article by Frank Mulligan titled "The exciting history of the exclamation mark!" (Taunton Daily Gazette, Feb. 22, 2010), makes these claims:

Archeologists believe they identified the first pre-historic exclamation mark in a cave painting unearthed in northern France depicting a lone, proud hunter poised to hurl a spear at a wooly mammoth on one wall's face.
On the opposing face of the cave's wall, as one proceeds deeper into the interior, the scene depicts a lone, not-so-proud hunter trampled underneath a wooly mammoth followed by that unmistakable symbol: a dot topped by a line pointing skyward.
...
The exclamation mark's first apparent use in writing dates back more than 5,000 years to the Egyptian hieroglyphs adorning the burial chamber in the Great Pyramid of Cheops at Giza.
The passage preceding what Egyptologists are convinced is the first exclamation mark used in an actual sentence translates roughly as: "It took a lot of work to build this thing!"
... there is evidence that Homer would break off during particularly exciting portions of "The Odyssey" to stand on a round rock and clasp both of his hands together over his head, much as a modern cheerleader will do to signify the letter "I," in order to approximate an exclamation mark for his audience.

For my part, I'm willing to accept cave paintings as a form of writing. However, the lack of support for this account may indicate it is as fanciful as the account featuring a highly mobile 'io'.
More recently (2 September 2015), a quite evidently well-researched and far from fanciful account by Keith Houston, available in an article titled "The mysterious origins of punctuation" at BBC's Culture site, traces the origins of the exclamation mark and other punctuation marks from a system devised in the 3rd century BCE by an Egyptian librarian named Aristophanes.
Aristophanes' system used three dots:

... aligned with the middle (·), bottom (.) or top (·) of each line. His 'subordinate', 'intermediate' and 'full' points corresponded to the pauses of increasing length that a practised reader would habitually insert between formal units of speech called the comma, colon and periodos. This was not quite punctuation as we know it – Aristophanes saw his marks as representing simple pauses rather than grammatical boundaries – but the seed had been planted.

By Houston's account, Aristophanes' system of dots was abandoned, never having been more than a method of marking pauses, before being resurrected by Christians in the 6th Century:

As it spread across Europe, Christianity embraced writing and rejuvenated punctuation. In the 6th Century, Christian writers began to punctuate their own works long before readers got their hands on them in order to protect their original meaning.

The early Christian punctuation was, however, confined to

... decorative letters and paragraph marks (Γ, ¢, 7, ¶ and others)

until, in the 7th Century, Isidore of Seville

rearranged the dots in order of height to indicate short (.), medium (·) and long (·) pauses respectively.
Moreover, Isidore explicitly connected punctuation with meaning for the first time: the re-christened subdistinctio, or low point (.), no longer marked a simple pause but was rather the signpost of a grammatical comma, while the high point, or distinctio finalis (·), stood for the end of a sentence.

Now writers began to embellish the three-dot system:

Some borrowed from musical notation, inspired by Gregorian chants to create new marks like the punctus versus (a medieval ringer for the semicolon used to terminate a sentence) and the punctus elevatus (an upside-down ';' that evolved into the modern colon) that suggested changes in tone as well as grammatical meaning. Another new mark, an ancestor of the question mark called the punctus interrogativus, was used to punctuate questions and to convey a rising inflection at the same time (The related exclamation mark came later, during the 15th Century.)

Having traced these origins, however, Houston glances over any individual account of the exclamation point:

This, then, was the state of punctuation at the height of the Renaissance: a mixture of ancient Greek dots; colons, question marks, and other marks descended from medieval symbols; and a few latecomers such as the slash and dash. ... when printing arrived in the mid-1450s, with the publication of Johannes Gutenberg's 42-line Bible, punctuation found itself unexpectedly frozen in time. Within 50 years, the majority of the symbols we use today were cast firmly in lead, never to change again: Boncompagno da Signa's slash dropped to the baseline and gained a slight curve to become the modern comma, inheriting its old Greek name as it did so; the semicolon and the exclamation mark joined the colon and the question mark; and Aristophanes's dot got one last hurrah as the full stop.

Houston's account is not necessarily at odds with other accounts, but he does seem far less inclined to speculative flights of fancy based on hesitation marks and scribal errors in ancient manuscripts. Additionally, he doesn't pair images of these unerasable and possibly accidental artifacts made on very expensive 'paper' with speculative graphics depicting the 'evolution' of...the question mark?

A: It does indeed come from Io as Wikipedia says.


text:
Q: NUnit tests refusing to run due to StackOverflowException I'm not sure what is causing the exception here at all.
I had a number of tests which make use of NUnit TestCases, and these tests were all running fine with no issues. I then wrote an additional test which is almost identical to the others apart from a few variable values, and now none of my tests will run due to a StackOverflowException.
[05/10/2018 10:10:00 Informational] ------ Run test started ------
[05/10/2018 10:10:00 Informational] NUnit Adapter 3.10.0.21: Test execution started
[05/10/2018 10:10:00 Informational] Running all tests in C:\test.dll
[05/10/2018 10:10:00 Informational] NUnit3TestExecutor converted 9 of 9 NUnit test cases
[05/10/2018 10:10:04 Error] The active test run was aborted. Reason: Process is terminated due to StackOverflowException.

[05/10/2018 10:10:04 Informational] ========== Run test finished: 0 run (0:00:04.661362) ==========

Tests in another test class will run, however none of the tests in this class will run even if I comment out the other tests.
As you can see from the code below, most of the tests are structurally identical to the others, save for the variable names being passed as parameters and testcases.
[TestFixture]
    class FluentAddressValidatorTest
    {
        private FluentAddressValidator validator;

        [OneTimeSetUp]
        public void Setup()
        {
            validator = new FluentAddressValidator();
        }

        [Test]
        public void FluentAddressValidatorAllowsValidAddressObject()
        {
            //Arrange
            FluentAddressValidator validator = new FluentAddressValidator();

            Address address = new Address();
            address = new Address
            {
                HouseNum = "1",
                HouseName = "Big House",
                StreetName = "Street",
                Locality = "Locality",
                Town = "Town",
                County = "County",
                Postcode = "NE11NM"
            };

            //Act
            ValidationResult result = validator.Validate(address);

            //Assert
            Assert.That(result.IsValid, Is.True);
        }

        [TestCase("1$")]
        [TestCase("1.")]
        [TestCase("32A.")]
        [TestCase("1        ")]
        public void FluentAddressValidatorDisallowsInvalidHouseNumber(string houseNum)
        {
            Address address = new Address
            {
                HouseNum = houseNum,
                HouseName = "House name",
                StreetName = "Street",
                Locality = "Locality",
                Town = "Town",
                County = "County",
                Postcode = "NE11NM"
            };

            validator.ShouldHaveValidationErrorFor(a => a.HouseNum, address);
        }

        [TestCase("House.Name")]
        [TestCase("House name.")]
        [TestCase("Housè")]
        [TestCase("")]
        [TestCase(" ")]
        [TestCase("House name House name House name House name House name")]
        public void FluentAddressValidatorDisallowsInvalidHouseName(string houseName)
        {
            Address address = new Address
            {
                HouseNum = "1a",
                HouseName = houseName,
                StreetName = "Street",
                Locality = "Locality",
                Town = "Town",
                County = "County",
                Postcode = "NE11NM"
            };

            validator.ShouldHaveValidationErrorFor(a => a.HouseName, address);
        }

        [TestCase("Street.Name")]
        [TestCase("Street name.")]
        [TestCase("Strèet")]
        [TestCase("")]
        [TestCase(" ")]
        [TestCase("Street name Street name Street name Street name Street name")]
        public void FluentAddressValidatorDisallowsInvalidStreetName(string streetName)
        {
            Address address = new Address
            {
                HouseNum = "1a",
                HouseName = "house",
                StreetName = streetName,
                Locality = "Locality",
                Town = "Town",
                County = "County",
                Postcode = "NE11NM"
            };

            validator.ShouldHaveValidationErrorFor(a => a.StreetName, address);
        }

        [TestCase("'Locality'")]
        [TestCase("Locality.")]
        [TestCase("Lòcality")]
        [TestCase("")]
        [TestCase(" ")]
        [TestCase("Locality Locality Locality Locality Locality Locality ")]
        public void FluentAddressValidatorDisallowsInvalidLocality(string locality)
        {
            Address address = new Address
            {
                HouseNum = "1a",
                HouseName = "house",
                StreetName = "Street name",
                Locality = locality,
                Town = "Town",
                County = "County",
                Postcode = "NE11NM"
            };

            validator.ShouldHaveValidationErrorFor(a => a.Locality, address);
        }

        [TestCase("'Town'")]
        [TestCase("Town.")]
        [TestCase("Tòwn")]
        [TestCase("")]
        [TestCase(" ")]
        [TestCase("Town Town Town Town Town Town Town Town Town Town")]
        public void FluentAddressValidatorDisallowsInvalidTown(string town)
        {
            Address address = new Address
            {
                HouseNum = "1a",
                HouseName = "house",
                StreetName = "Street name",
                Locality = "Locality",
                Town = town,
                County = "County",
                Postcode = "NE11NM"
            };

            validator.ShouldHaveValidationErrorFor(a => a.Town, address);
        }

        [TestCase("'County'")]
        [TestCase("County.")]
        [TestCase("Còunty")]
        [TestCase("")]
        [TestCase(" ")]
        [TestCase("County County County County County County")]
        public void FluentAddressValidatorDisallowsInvalidCounty(string county)
        {
            Address address = new Address
            {
                HouseNum = "1a",
                HouseName = "house",
                StreetName = "Street name",
                Locality = "Locality",
                Town = "Town",
                County = county,
                Postcode = "NE11NM"
            };

            validator.ShouldHaveValidationErrorFor(a => a.County, address);
        }

        [TestCase("'Postc0de'")]
        [TestCase("Ne11111.")]
        [TestCase("NXXXX12")]
        [TestCase("NXXXX!£2")]
        [TestCase("")]
        [TestCase(" ")]
        [TestCase("NE1                  1BN")]
        public void FluentAddressValidatorDisallowsInvalidPostcode(string postcode)
        {
            Address address = new Address
            {
                HouseNum = "1a",
                HouseName = "house",
                StreetName = "Street name",
                Locality = "Locality",
                Town = "Town",
                County = "County",
                Postcode = postcode
            };

            validator.ShouldHaveValidationErrorFor(a => a.Postcode, address);
        }
    }

FluentAddressValidator
public class FluentAddressValidator : AbstractValidator<Address>
    {
        private readonly string alphanumericalSpaceCaseInsensitiveRegex = "^[a-zA-Z0-9 ]*$";
        private readonly string alphabeticalSpaceCaseInsensitiveRegex = "^[a-zA-Z ]*$";

        public FluentAddressValidator()
        {
            RuleFor(a => a.HouseNum).NotEmpty().MaximumLength(8).Matches(alphanumericalSpaceCaseInsensitiveRegex) //Not empty string, alphanumeric, allows spaces
                .WithMessage("House number must be alphanumerical only.");
            RuleFor(a => a.HouseName).NotEmpty().MaximumLength(32).Matches(alphabeticalSpaceCaseInsensitiveRegex) //Not empty string, alphabetical, includes spaces
                .WithMessage("House name must be alphabetical only.");
            RuleFor(a => a.StreetName).NotEmpty().MaximumLength(32).Matches(alphabeticalSpaceCaseInsensitiveRegex) //Not empty string, alphabetical, includes spaces
                .WithMessage("Street name must be alphabetical only.");
            RuleFor(a => a.Locality).NotEmpty().MaximumLength(32).Matches(alphabeticalSpaceCaseInsensitiveRegex) //Not empty string, alphabetical, includes spaces
                .WithMessage("Locality must be alphabetical only.");
            RuleFor(a => a.Town).NotEmpty().MaximumLength(32).Matches(alphabeticalSpaceCaseInsensitiveRegex) //Not empty string, alphabetical, includes spaces
                .WithMessage("Town must be alphabetical only.");
            RuleFor(a => a.County).NotEmpty().MaximumLength(32).Matches(alphabeticalSpaceCaseInsensitiveRegex) //Not empty string, alphabetical, includes spaces
                .WithMessage("County must be alphabetical only.");
            RuleFor(a => a.Postcode).NotEmpty().MaximumLength(16).Must(Common.IsValidUkPostcode) //Not empty string, is valid uk postcode
                .WithMessage("Postcode must follow valid UK postcode format.");
        }

    }

IsValidUkPostcode
public static bool IsValidUkPostcode(string postcode)
        {
            postcode = postcode.Replace(" ", string.Empty);
            postcode = postcode.ToUpper();

            Regex r = new Regex(@"([Gg][Ii][Rr] 0[Aa]{2})|((([A-Za-z][0-9]{1,2})|(([A-Za-z][A-Ha-hJ-Yj-y][0-9]{1,2})|(([A-Za-z][0-9][A-Za-z])|([A-Za-z][A-Ha-hJ-Yj-y][0-9][A-Za-z]?))))\s?[0-9][A-Za-z]{2})");

            if (r.IsMatch(postcode))
            {
                return true;
            }
            else
            {
                return false;
            }
        }

A: The cause of the StackOverflowException was due to the presence of Properties within the Address class that accidently made calls to itself recursively. This was not an issue with FluentValidation or NUnit.
For example:
public string Street
{
    get
    {
        return Street;
    }
    set
    {
        Street = value;
    }
}

This causes recursion and eventually will cause a stack overflow. To prevent this, have a private backing field that the property can delegate the data to.
private string street;

public string Street
{
    get
    {
        return this.street;
    }
    set
    {
        this.street = value;
    }
}

redpajama_set_name: RedPajamaStackExchange


text:
Q: web graph for a set of websites using python I have exteracted a set of urls which are on same topic. I want to find links between them so that i can form graph using python. the urls or websites would represent as nodes and links between them, represent as edges. please help me..

A: You can follow this simple approach -
Parse web pages using BeautifulSoup[1] and keep anchor tags' href property stored in a nested list(assume lst). So, if a web page(assume web1) links to 3 other web pages(assume with links href1, href2, href3), then -
lst['web1'][0] = 'href1'
lst['web1'][1] = 'href2'
lst['web1'][2] = 'href3'

Similarly parse other web pages and created lists for them. This web1 can be hrefx for webx. Hope you got the idea.
[1] http://www.crummy.com/software/BeautifulSoup/


text:
Q: Why addEventListener doesn't get global var? Why "multiply" button works only if I put both var into function, but not with global var?
Here are my codes:

var first = document.getElementById("firstN").value;
var second = document.getElementById("secondN").value;

document.getElementById("multiply").addEventListener("click", function() {
  document.getElementById("answer").innerHTML = first * second;
});

1st Number: <input id="firstN" type="number">

2nd Number: <input id="secondN" type="number">

<button id="multiply">Multiply</button>
<button id="divide">Divide</button>

The result is:

A: The problem is that you need to find out the values of first and second when you clicked the button.
document.getElementById("multiply").addEventListener("click", function(){
    var first = document.getElementById("firstN").value;
    var second = document.getElementById("secondN").value;
    document.getElementById("answer").innerHTML = first * second;
});

 document.getElementById("multiply").addEventListener("click", function () {
        var first = document.getElementById("firstN").value;
        var second = document.getElementById("secondN").value;
        document.getElementById("answer").innerHTML = first * second;
    });

1st Number: <input id="firstN" type="number">

2nd Number: <input id="secondN" type="number">

<button id="multiply">Multiply</button>
<button id="divide">Divide</button>

The result is:

A: If you want to create the variables first and second out of the event handler you most select only the elements (In this example I use document.querySelector()).
var first = document.querySelector('#firstN');
var second = document.querySelector('#secondN');

Check in the answer that using document.querySelectorAll() you can select multiple elements to attach at once the click event handler.. and access to the elements value attribute with in the function handler to solve Multiply and Divide in one method.
Code example:

var first = document.querySelector('#firstN');
var second = document.querySelector('#secondN');

document
  .querySelectorAll('#multiply, #divide')
  .forEach(function (elem) {
    elem.addEventListener('click', function () {
        var result =  {
          'multiply': first.value * second.value,
          'divide': first.value / second.value
        };
        document.querySelector('#answer').innerHTML = result[elem.id];
    });
  });

1st Number: <input id="firstN" type="number">

2nd Number: <input id="secondN" type="number">

<button id="multiply">Multiply</button>
<button id="divide">Divide</button>

The result is:

Notice that as explained by @Alexandru-Ionut Mihai the value of the variables first and second should be assigned with in the event handler function.

A: The problem is that when the page loads and parses it stores the value of variables, first and second which is null at the moment.
So you have to declare or assign values to them inside the click event in order to assign the values of inputs into the variables.
Also the format of the input by default in dom is string, so you have to handle it too, by using the parseInt/parseFloat methods which will change the string to numbers.

document.getElementById("multiply").addEventListener("click", function() {
  var first = document.getElementById("firstN").value;
  var second = document.getElementById("secondN").value;
  document.getElementById("answer").innerHTML = parseFloat(first) * parseFloat(second);
});

1st Number: <input id="firstN" type="number">

2nd Number: <input id="secondN" type="number">

<button id="multiply">Multiply</button>
<button id="divide">Divide</button>

The result is:

For more information you can refer to these articles:

*

*parseInt / parseFloat

*string / number

*addEventListener

A: You need to set value of first and second inside addEventListner.

window.onload = function () {

    document.getElementById("multiply").addEventListener("click", function () {
        var first = document.getElementById("firstN").value;
        var second = document.getElementById("secondN").value;
        document.getElementById("answer").innerHTML = first * second;
    });
}

1st Number: <input id="firstN" type="number">

2nd Number: <input id="secondN" type="number">

<button id="multiply">Multiply</button>
<button id="divide">Divide</button>

The result is:

Please add more clarity to question if you are looking for some different answer.


text:
Q: Non-modal WPF dialog hosted in a Win32 app doesn't receive keyboard events I've got a WPF dialog that I want to display in a Win32 app as a non-modal Window.
Calling window.Show() correctly displays the window, and all mouse events are handled properly by it, but all keyboard event are handled by the parent Win32 window, so that even if a user has given focus to a textbox, any typed text shows up in the parent Win32 window!
This seems to be a known problem in WinForms/WPF interop, and is fixed in that case by calling ElementHost.EnableModelessKeyboardInterop before displaying the dialog. This causes a new message filter to be added to the WinForms message loop, so that keyboard events can be intercepted and appropriately routed to the WPF dialog.
Unfortunately my host application is not a WinForms app, so I don't have the option to call EnableModelessKeyboardInterop. Is there any way to do a similar thing in a Win32 app?

A: You can forward the keyboard messages, but you'll need to do the work yourself.
The basic idea is as follows:

*

*Once your WPF window has been created and shown, get its HwndSource:
HwndSource source = HwndSource.FromVisual(wnd) as HwndSource;

*In your message loop, whenever you get a keyboard message, cast the HwndSource to IKeyboardInputSink, and call the appropriate method.
Basically, if you get a WM_KEYDOWN, you should call TranslateAccelerator(), or if you get a WM_CHAR you should call TranslateChar(). The documentation for IKeyboardInputSink isn't great, but it does specify which methods handle which messages. The method will return true if it has handled message, so you will know if you need to process the message in the Win32 side or not.


text:
Q: Set scrolling limits for fixed background image? Is there a way to set limits for how far a fixed background image can "scroll" down a page? Effectively, is there a way to change the background attachment to static once the the bottom of background image is say 10px away from the bottom edge of its div container?
In the code below, for example, how can I get the coral gradient (just a placeholder for an image) to stop scrolling with the page once it gets 10vh away from the border between the red and yellow divs? (CSS only is preferable, though I am also open to JS solutions)

.red {
  position: absolute;
  top: 0;
  height: 100vh;
  width: 100vw;
  background: red fixed linear-gradient(lightcoral, lightcoral) 45vw 20vh / 20vh 20vh no-repeat;
}

.yellow {
  position: absolute;
  top: 100vh;
  height: 100vh;
  width: 100%;
  background-color: yellow;
}

Thanks!

A: Aidan!
My approach uses an img tag instead of rendering it as background, and the magic is done with Position sitcky.

You can play with padding of its container to adjust the border offset.
Hope this helps.
Happy conding! ;)


text:
Q: About dual key concurrent hashmap in java I need dual key concurrent hashmap.
My first try is just using java.util.concurrent.ConcurrentHashMap. Like this
ConcurrentHashMap<String, String> map = new ConcurrentHashMap<>();
map.put("key1" + "|" +"key2", "value");
String vaule = map.get("key1" + "|" +"key2");

but I think this is ugly.
My Second try is using Object as Key. Like this
@Data
public class DualKey {
    private final String key1;
    private final String key2;
}

map.put(new DualKey("key1", "key2"), "value");
String vaule = map.get(new DualKey("key1", "key2"));

Last try is create DualkeyConcurrentHashMap. I just need put, get, containsKey.
public class DualkeyConcurrentHashMap<K1, K2, V>  {
    private final ConcurrentHashMap<K1, ConcurrentHashMap<K2, V>> map
                                                    = new ConcurrentHashMap<>();

    public V put(K1 key1, K2 key2, V value) {
        ConcurrentHashMap<K2, V> subMap
                    = map.computeIfAbsent(key1, k -> new ConcurrentHashMap<>());
        return subMap.put(key2, value);
    }

    public V get(K1 key1, K2 key2) {
        ConcurrentHashMap<K2, V> subMap = map.get(key1);
        return null == subMap ? null : subMap.get(key2);
    }

    public boolean containsKey(K1 key1, K2 key2) {
        return null != get(key1, key2);
    }
}

Is it better and perfectly thread safe?
(I can't decide all method need synchronized.)
Is there another recommended way?

A: All options are thread-safe, which is guaranteed by ConcurrentHashMap. Important fact to note is:

However, even though all operations are thread-safe, retrieval
  operations do not entail locking, and there is not any support for
  locking the entire table in a way that prevents all access. This class
  is fully interoperable with Hashtable in programs that rely on its
  thread safety but not on its synchronization details.

The natural way to implement a dual key map would be to provide an object, so I would go with the second one, only that I would make DualKey generic.
The first one couples implementation and design (string1 "|" + string1 key format) and does not allow you to change types used as keys easily.
The third one uses much more instances of ConcurrentHashMap than needed.


text:
Q: NFC Readers with Bluetooth Not sure if this is a Stack Overflow question (if anyone knows a more apropiate section of StackExchange I'll be happy) but all questions on NFC Readers seamed to be here so, here I go:
I want to use NFC-Tags for a project and need a reader. While more and more phones are capable of reading such tags, any older phone is not. These phones do however usually have Bluetooth. So what I am looking for is a NFC Reader that can connect to a phone via Bluetooth.
I thought this would be a common device but to my surprise I did not find much. Readers usually connect via usb (as these do). There is at least one device that does use Bluetooth, the Blueberry UHF, but I could not find any retailer that sells it.
So, my question would be this: Is there a reason that there are almost no such devices or am I just looking at the wrong places?

A: I know I am late answering this questions, but maybe my response will help others who are searching for the same thing. What you are looking for is available from Serialio. There are multiple Bluetooth NFC readers available. The BlueBerry is re-branded with the Scanfob brand.
Here is a link to the updated Scanfob NFC page (the above link posted earlier no longer works): https://serialio.com/products/rfid/readerwriters/scanfob%C2%AE-nfc-bb2
There are multiple apps available that interface with the readers. This really depends on what you want to do with data from your reads.
Heres' an example of attendance managment solution using an NFC reader on Android:
https://serialio.com/products/mobile/software/MobileGrid/Android/use/TimeTrack/MG_TimeTrack_Android.php
There's a lot more. I just don't have the reputation to add more links yet.

A: The type of device you refer to is available here: https://serialio.com//store/index.php?cPath=89&osCsid=nep7av4i0431r39eqdl23oh2i7.
The reason you struggle to find a Bluetooth enabled device is because the peripheral market for NFC/RFID readers are targeted at the desktop embedded market where USB/RS232 cable options are cheaper/easier/stable offerings people are familiar with. The driver stack provided with a cabled device can also do a lot of the hard work in dealing with the incoming data.
There are however a few companies on the market producing RS232 to Bluetooth bridges which means you can try and port peripherals across to this using Bluetooth. Although you'll be able to pair the devices, you'll then need to write the software that can interrupt in the incoming payload over the Bluetooth serial port connection so it'll be a lot more work to get a platform like this up and running - especially with older devices. However it is possible if required.

A: What possible problem would a NFC reader that connects to a phone via bluetooth solve? The phone is not going to know anything about NFC, it does not have the required software or stack.
Sure, you could write that software (possibly) but to what end? The unit you linked to is what you are after, sure, but it's for a very specialised purpose (i.e. you have to write the s/w at the other end).
It's likely to be cheaper (in time and money) to just buy a phone that supports NFC rather then trying to upgrade a unit that does not.


text:
Q: Getting the average of a database column from matching records in CakePHP 2.9 Is there a way (beyond completely custom SQL) to find the average of a table column from records that match certain conditions in CakePHP 2.9?
For example, I can find a list of Fields easily by calling the Field model:
$fields = $this->Field->find('all', array(
    'conditions' => array(
        'User.username' => 'John Doe',
        'Report.created' => '2018-01-01'
    )
);

However, what I really want to get is the average of Field.value, for all records that match.
What I might do normally is to do a raw SQL query;
$average = $this->Field->query('
    select avg(f.value) as average from fields f
      left join users u on (f.user_id = u.id)
      left join reports r on (f.report_id = r.id)
      where u.username = "John Doe" and r.created = "2018-01-01"
');

However, I don't necessarily know what the condition fields are are, and I would like to use the power of the CakePHP ORM to build the query.
Is there a way to calculate this average from a Model::find?

A: Assuming you have followed Cakephp conventions. You can do Average of a field as below.
$average = $this->Field->find('all', array(
'fields' => array('AVG(Field.value) as average'),
'conditions' => array('User.username' => 'John Doe', 'Report.created' => '2018-01-01'),
'contain' => array('User', 'Report')
));

Hope you will get the idea.


text:
Q: Python:synthetic classes I can make a synthetic class cls1 that inherits from cls.
>>> class cls(object):
...     def func(self,arg):
...         print 'func',arg
>>> def func1(self):
...     print "func 1 of cls1"
>>> def func2(self):
...     print "func2 of cls1"
>>> d=dict(func1=func1,func2=func2)
>>> cls1=type('cls1',(cls,),d)

Everything works as expected:
>>> obj=cls1()
>>> obj.func(7)
func 7

I can also replace cls1 with FOO:
>>> cls1=type('FOO',(cls,),d)

that gives me:
'cls1': <class '__main__.FOO'>,

Does this (changing __name__ variable) alter the behavior of cls1 and how (everything still works fine)?

A: You're just changing the name of your class, so it should matter only if you rely on the name somehow:
>>> type(obj)
__main__.FOO
>>> isintance(obj, cls1)
True

That works fine, but what about pickling (that I think rely on the name) ?
For example, before the name change, you can pickle obj without any problem. You can't afterwards.
PicklingError: Can't pickle <class '__main__.FOO'>: it's not found as __main__.FOO


text:
Q: Laravel: Returning a view from a controller I'm trying to learn how to use Laravel 5, but I've bumped into a problem. I've created the following code so far:
under app/HTTP/routes.php:

<?php

Route::get('/', 'MyController@home');

Created my own MyController.php file under app\Http\Controllers and added the following code to the controller:
<?php

namespace App\Http\Controllers;

use Illuminate\Routing\Controller as BaseController;

class MyController extends BaseController
{
    public function home()
    {
        $name = "John Doe";
        return View::make("index")->with("name", $name);
    }
}

When I run the app I get the error:
FatalErrorException in MyController.php line 12:
Class 'App\Http\Controllers\View' not found

What am I doing wrong?

A: Change
return View::make("index")->with("name", $name);

To
return \View::make("index")->with("name", $name);

or Even better
return view("index",compact('name'));

UPDATE
View is a Facade, a wrapper class, and view() is a helper function that retrives a view instance.


text:
Q: Prove that: $\sqrt [3]{36}<\ln 28<\sqrt [3]{37}$
Prove that:
$$\sqrt [3]{36}<\ln 28<\sqrt [3]{37}$$

This inequality is the result of an integral representation/inequality.
I lost access to the article that mentioned this inequality.  Now I want to prove it myself.  Using series is the standard way.  However, this involves heavy calculations, so it's almost useless. We know that,
$$\ln 28=2\ln 2+\ln 7$$
From here, it is necessary to evaluate the $\ln2$ and $\ln 7$ numbers independently. More work is required.

*

*If you've seen this inequality before, please share the solution with us.  Presumably this will be the Integral representation.

*If you have made any solution that requires as little computation as possible, please share it with us.

*The question is open to all solutions involving elementary techniques or advanced techniques.
Less computational solutions are preferred.

A: For the left inequality:
We have
$$\ln 28 = 5 \ln 2 - \ln(8/7)
\ge 5\ln 2 - 1/7$$
where we have used $\ln(1 + u) \le u$ for all $u \ge 0$.
From
$$0 \le \int_0^1 \frac{x^2(1 - x)^3}{1 + x}\,\mathrm{d} x = 8\ln 2 - \frac{83}{15},$$
we have
$\ln 2 \ge \frac{83}{120}$.
(Note: Alternatively,
we may use $\ln \frac{1+x}{1-x}
\ge 2x + \frac23 x^3$ ($3$-th order Taylor approximation) to get
$\ln 2 \ge \frac{56}{81}$ by letting $x = 1/3$.)
Thus, we have
$$\ln 28 \ge 5 \cdot \frac{83}{120} - 1/7 = \frac{557}{168}.$$
Let $A = \sqrt[3]{36}$ and $B = 10/3$. Then $A < B$. We have
$$A = B - \frac{B^3 - A^3}{B^2 + BA + A^2} \le B - \frac{B^3 - A^3}{3B^2} = \frac{743}{225}.$$
(Note: $\sqrt[3]{36} = 3\sqrt[3]{1 + 1/3} \le 3(1 + 1/9) = 10/3$ by Bernoulli inequality.)
Since $\frac{743}{225} < \frac{557}{168}$, we have $36^{1/3} < \ln 28$.
$\phantom{2}$
For the right inequality:
Using $37 \cdot 27 = 999$, we have
$$\sqrt[3]{37} = \sqrt[3]{999/27} = \frac{10}{3}\sqrt[3]{999/1000}
\ge \frac{10}{3} \cdot \frac{3 \cdot 999/1000}{2\cdot 999/1000 + 1} = \frac{4995}{1499}$$
where we have used
$$u^{1/3} = \frac{u}{\sqrt[3]{u \cdot u \cdot 1}} \ge \frac{u}{(u+u+1)/3} = \frac{3u}{2u + 1}.$$
It suffices to prove that
$$\ln 28 < \frac{4995}{1499}.$$
I don't have a nice approach to deal with it.
Hope it helps.

A: I am trying an approximation with the simple tools...
$$\ln28=3\left(\ln(1+\frac{1}{2})-\ln(1-\frac{1}{2})\right)+\ln(1+\frac{1}{27})\approx3\sum_{n=0}^{N}\frac{1}{(2n+1)2^{2n}}+\sum_{m=1}^{M}\frac{(-1)^{m+1}}{m\;27^{m}}.$$
Now, I assume that $4$ arithmetic operation calculator can be used:
Lower bound is easy: $N=3, M=2\implies \ln28>3.33\implies \ln^328>36.926037>36.$
Upper bound: $N=5, M=3\implies \ln28<3.33213+3\sum_{n=6}^{\infty}\frac{1}{(2n+1)2^{2n}}\implies \ln28<3.33213+\frac{3}{13}\sum_{n=6}^{\infty}\frac{1}{4^{n}}\implies\ln28<3.33221\implies\ln^328<36.9997<37.$


text:
Q: Firestore - querying Subcollections with startAfter does not set the cursor Querying a Subcollection always return all list when using:

*

*startAt

*startAfter
Sample query
await countryCollection()
  .doc('Indonesia')
  .collection('states')
  .startAfter('Riau')
  .limit(10)
  .get();


text:
Q: Default tabs in Ajax I'm trying to load a default tab in the tabbed ajax code that I've got, this is the source from the head tags

And this is what I'm using in HTML:

TEAM TRAINING PROGRAM

VIRTUAL EDUCATION AND COACHING PROGRAM

PERSONAL COACHING PROGRAM

The page in question is :
http://www.hastiefitness.com.au/programs/
The default tab is meant to be the middle one, which is tab-2.
How would I be able to perform this? I've searched and haven't been able to get it working at all.

A: Looks like the plugin used does not have any direct support for setting active tab so once the plugin is initialized trigger a click event on the desired anchor element
jQuery(function(){
    $('.tabs').fwd_tabs();
    $('.tabs a[href="#tab-2"]').click()
})

Demo: Fiddle


text:
Q: Sumatoria en Haskell necesito hacer la sumatoria desde i = 1 hasta n de i^n en Haskell.
Alguien tiene idea o me puede ayudar a hacerlo?.. Estoy haciendo un proyecto y necesito eso en haskell que no tengo mucha idea.

A: Buenas noches, una posible solución es esta:
sumtoria i n | i==n = i**n
|otherwise = i**n + sumtoria (i+1) n

Cuando i=n hace la potencia, en los otros casos va acumulando las potencias mientras aumenta i. Sólo se contempla metiendo valores de i menores a n.
Una solución más elegante podría ser utilizando funciones de orden superior, pero eso ya es otro tema.

A: La forma más simple:
sumatoria :: Integer -> Integer
sumatoria n = sum [ i^n | i <- [1..n]]

A: Buenos dias una posible respuesta para tu problema seria
suma a b | a==b = a**b|otherwise = a**b + suma (a+1) b

Main
suma (2,3)

Espero te sirva


text:
Q: Does there exist a polynomial indicator function over $\mathbb{Z}_p[x_1,\dots,x_{p^3}]$ of degree at most $O(p^2)$? The Problem
Let $p$ be a prime. Does there exist a $p^3$-variable polynomial $P$ over $\mathbb{Z}_p[x_1,\dots,x_{p^3}]$ such that

*

*$P(\boldsymbol{0}) \equiv 0 \ (p)$

*$P(\boldsymbol{x}) \equiv 1 \ (p)$ for any $\boldsymbol{x} \ne \boldsymbol{0}$.

*$\deg{P} \in O{(p^2)}$ (its degree is at most some $2$-degree polynomial in $p$)

Meaning that $P$ is equivalent to the indicator function (or $1-$ the indicator function) over $\mathbb{Z}_p[x_1,\dots,x_{p^3}]$, and has degree of at most $O(p^2)$.
Fermat's Little Theorem
Due to Fermat's little theorem, for any prime $p$:
$$a^{p-1} \equiv \begin{cases}1 \quad \text{ if } a \not\equiv 0 \\ 0 \quad \text{ if } a\equiv 0\end{cases} \quad (p)$$
Trial and error
I have tried the following potential candidates, but they all fail in at least one of these aspects:
Trial 1:
$$P(\boldsymbol{x}) \stackrel{?}{=} \left(\sum_{i=1}^{p^3} x_i^{p-1}\right)^{p-1}$$

*

*$P(\boldsymbol{0}) \equiv 0 \ (p) \quad \checkmark$

*But if $\boldsymbol{x} = (\underbrace{1,\dots,1}_p,\underbrace{0,\dots,0}_{p^3-p})$, then

$$P(\boldsymbol{x}) = \left(\sum_{i=1}^{p} 1 + \sum_{i=p+1}^{p^3} 0 \right)^{p-1} = p^{p-1} \equiv 0^{p-1} \equiv 0 \quad (p)$$
So in this case, condition 2 fails to hold.
Trial 2:
$$P(\boldsymbol{x}) \stackrel{?}{=} 1-\prod_{i=1}^{p^3} (1-x_i)^{p-1}$$

*

*Clearly holds in this case. $\quad \checkmark$

*Also holds, $P(\boldsymbol{x}) = 1$ exactly if none of the $x_i$'s are $0$, a.k.a., if $\boldsymbol{x} \ne \boldsymbol{0}$. $\quad \checkmark$

*However Condition 3 fails here. The polynomial's degree is $p^3(p-1) = O(p^4)$.
Trial 3:
$$P(\boldsymbol{x}) \stackrel{?}{=} \left(\sum_{\begin{matrix}I \subseteq \{1,\dots,p^3\} \\ |I| = kp \\ k \in \{1,\dots,p^2\}\end{matrix}} \left( \sum_{i\in I} x_i^{p-1}  \right)^{p-1}\right)^{p-1} + \left(\sum_{i=1}^{p^3} x_i^{p-1}\right)^{p-1}$$

*

*$P(\boldsymbol{0}) \equiv 0 \ (p) \quad \checkmark$

*$P(\boldsymbol{x}) \equiv 1  \ (p)$  also holds here. The right term is the exact same as the entire polynomial in Trial 1; and the left term equals $1$ for exactly the $\boldsymbol{x}^{p-1}$'s where number of $1$'s it contains is divisible by $p$. $\quad \checkmark$

*However $\deg{P} = (p-1)^3 \in O(p^3)$. (But, we're getting closer. The last example was $O(p^4)$.)

Note:
$$P(\boldsymbol{x}) \stackrel{?}{=} 1-I(\boldsymbol{x} = 0)$$
where $I$ is the real indicator function.
However, $P$ needs to be a polynomial, so I can't just use the "regular" indicator function.
Context
I am trying to prove a theorem using the Chevalley-Warning theorem, which requires certain conditions for the degrees polynomials. The main issue is actually to construct such a polynomial, and once that's done, the theorem would basically "prove itself". However, it is possible, that such a polynomial doesn't exist.

A: Since you bring up Chevalley-Warning how about the following counting argument. Here $V$ stands for the vector space $\Bbb{Z}_p^n$. In your case $n=p^3$ but the argument can be made more generally.
Observation. Consider the monomial $f(x_1,\ldots,x_n)=\prod_{i=1}^nx_i^{a_i}$ where $0\le a_i<p$ for $i$. Unless $a_i=p-1$ for all $i$, we have
$$\sum_{\mathbf{x}\in V}f(\mathbf{x})=0\in\Bbb{Z}_p.$$
Proof. Assume that for some index $i_0$ we have $m:=a_{i_0}<p-1$. If $m=0$ then the sum $\sum_{x\in\Bbb{Z}_p}x^m=p\cdot 1=0$. Otherwise there exists an element $a\in \Bbb{Z}_p\setminus\{0\}$ such that $a^m\neq1$ (the polynomial $x^m-1$ can have at most $m$ zeros in the field $\Bbb{Z}_p$). But $x$ ranges over the field $\Bbb{Z}_p$ as $ax$ does, so the monomial sum
$$
S=\sum_{x\in\Bbb{Z}_p}x^m=\sum_{x\in\Bbb{Z}_p}(ax)^m=a^mS
$$
implying that $S=0$. The claim follows from this because
$$
\sum_{\mathbf{x}\in V}f(\mathbf{x})=\prod_{i=1}^n\left(\sum_{x\in\Bbb{Z}_p}x^{a_i}\right)
$$
and if any $a_i<p-1$ then the corresponding factor vanishes and hence the entire sum.
The impossibility of your task follows from this. We can reduce the degree of any polynomial in $\Bbb{Z}_p[x_1,\ldots,x_n]$ by replacing any instance of $x_i^p$ with $x_i$ with the consequence that all the terms of your polynomial $P$ satisfy the constraints in the observation. A corollary of the observation is that the sum of the values of the polynomial $P$ over $V$ is zero unless the term $(x_1\cdots x_n)^{p-1}$ appears. For your indicator function the sum of its values is $-1\in\Bbb{Z}_p$. Hence it must have degree at least $n(p-1)=p^3(p-1)$.

When written as a polynomial, the characteristic function of a subset $S\subset V$ (after substituting $x_i^p$ and highe with lower degree equivalents) contains the term $(x_1\cdots x_n)^{p-1}$ unless the number of elements of $S$ is a multiple of $p$. In other words, the degree of the polynomial is then equal to $n(p-1)$.

The OP's attempt, trial #3, fails to work as hoped. If all the entries of the vector $\mathbf{x}$ are non-zero, then each sum
$$\sum_{i\in I}x_i^{p-1}=\sum_{i\in I, x_i\neq0}1=|I|\cdot1,$$
where $p\mid |I|$, automatically vanishes, as does the entire sum. Trial #2 is the only one that works, and it has degree $n(p-1)=p^3(p-1)$ as described by the observation and its corollary.


text:
Q: Mathematica 12.1 trial version, very slow to evaluate a property in multiple pictures I am a new mathematica user.
I am using the following code to measure the internal rectangle width in some images. When I run mathematica for $1$ image, it takes a short time. Also, it works and it shows the results for more than one image. However, it takes (EXTREMELY) long time to show the results, especially when the number of picture more than $5$. It took around $25$ minutes to process around $35$ pictures!
One possibility, that my requirement from mathematica is too much, and it is normal to process $35$image/$25$min.
One possibility, that I use mathematica in a wrong way to get the result; I go to Evaluation bar then Evaluate Notebook option.

One possibility, that the code can be modified in a way it will work faster.
One possibility, that this version of mathematica (12.1) has an issue.
PLEASE CHECK THE FOLLOWING:
ClearAll[vDilate, internalRectangles, dataSet]

vDilate =
  ColorNegate@
    Dilation[MorphologicalBinarize@#,
     ConstantArray[1, {ImageDimensions[#][[1]], 1}]] &;

internalRectangles[w_ : 1] :=
  Rectangle @@@
    Values[ComponentMeasurements[
      SelectComponents[
       vDilate@#, #CaliperWidth >
          w && #AdjacentBorders == {Bottom, Top} &], "BoundingBox"]] &;

dataSet[w_ : 1] :=
  ComponentMeasurements[
    SelectComponents[
     vDilate@#, #CaliperWidth >
        w && #AdjacentBorders == {Bottom, Top} &], {"BoundingBox",
     "CaliperWidth"}, "Dataset"] &;

{img1, img2, img3, img4, img5, img6} =
 Import /@ {"D:\\SHARGAM\\167716 6 SDGM Comp 2 HRDH B2 4200 rpm + TB) \
(61-65 C) 2 4046 08-03-12  10-06-2020.jpg",
   "D:\\SHARGAM\\252929 6 SDGM Comp 2 HRDH B2 4200 rpm + TB) (75-80 \
C) 2 4048 09-16-57  11-06-2020.jpg",
   "D:\\SHARGAM\\232614 6 SDGM Comp 2 HRDH B2 4200 rpm + TB) (70-75 \
C) 2 4051 03-15-54  11-06-2020.jpg",
   "D:\\SHARGAM\\211778 6 SDGM Comp 2 HRDH B2 4200 rpm + TB) (70-75 \
C) 2 4051 21-05-53  10-06-2020.jpg",
   "D:\\SHARGAM\\192633 6 SDGM Comp 2 HRDH B2 4200 rpm + TB) (70-75 \
C) 2 4052 15-25-53  10-06-2020.jpg",
   "D:\\SHARGAM\\172707 6 SDGM Comp 2 HRDH B2 4200 rpm + TB) (65-70 \
C) 2 4050 09-31-56  10-06-2020.jpg"}

ClearAll[dataSet2]
dataSet2 =
  MaximalBy[#CaliperWidth &]@
    ComponentMeasurements[
     SelectComponents[
      vDilate@#, #AdjacentBorders == {Bottom, Top} &], {"BoundingBox",
       "CaliperWidth"}, "Dataset"] &;

dataSet2 /@ {img1, img2, img3, img4, img5, img6}

Where;
"D:\SHARGAM\167716 6 SDGM Comp 2 HRDH B2 4200 rpm + TB) (61-65 C) 2 \
4046 08-03-12  10-06-2020.jpg", "D:\SHARGAM\252929 6 SDGM Comp 2 \
HRDH B2 4200 rpm + TB) (75-80 C) 2 4048 09-16-57  11-06-2020.jpg", \
"D:\SHARGAM\232614 6 SDGM Comp 2 HRDH B2 4200 rpm + TB) (70-75 C) 2 \
4051 03-15-54  11-06-2020.jpg", "D:\SHARGAM\211778 6 SDGM Comp 2 \
HRDH B2 4200 rpm + TB) (70-75 C) 2 4051 21-05-53  10-06-2020.jpg", \
"D:\SHARGAM\192633 6 SDGM Comp 2 HRDH B2 4200 rpm + TB) (70-75 C) 2 \
4052 15-25-53  10-06-2020.jpg", "D:\SHARGAM\172707 6 SDGM Comp 2 \
HRDH B2 4200 rpm + TB) (65-70 C) 2 4050 09-31-56  10-06-2020.jpg"
are the path of the images to be processed, they look like this;

It took around $3.5-4$ minutes for those $6$ images!

If I need to find the caliperwidth of $1000$ images, it may take $1000$ life-times!

You can see my previous problem, kglr helped a lot. Many thanks to kglr.

AGAIN, I am a new mathematica user. (2 days).

Any help/suggestion to modify the code, or correcting me on how to evaluate the outputs, would be really appreciated. THANKS!


text:
Q: How to convert arguments of a function into a class in Python? I have function which has 10 argument but each time i call a function i dont need to pass all the 10 arguments as all the 10 arguments are not relevant each time the function is called.
def function(arg1:Optional[int] =0,arg2:Optional[int] =0,arg3:Optional[int] =0,
            arg4:Optional[int] =0,arg5:Optional[int] =0, arg6:Optional[str] =None,
            arg7:Optional[str] =None,arg8:Optional[str]=None,arg9:Optional[str]=None,arg10:Optional[str] =None)

    pass

How to convert these arguments into a class and pass that class in the function as an argument each time the function needs to be called so that only relevant arguments get passed each time the function is called?
If any one can give some hints pls.

A: Here's how you might bundle all of those argument values into a dataclass:
from dataclasses import dataclass
from typing import Optional

@dataclass
class FunctionArgs:
    arg1: Optional[int] = 0
    arg2: Optional[int] = 0
    arg3: Optional[int] = 0
    arg4: Optional[int] = 0
    arg5: Optional[int] = 0
    arg6: Optional[str] = None
    arg7: Optional[str] = None
    arg8: Optional[str] = None
    arg9: Optional[str] = None
    arg10: Optional[str] = None

def function(args: FunctionArgs) -> None:
    pass

You'd then call the function like this:
function(FunctionArgs(arg4=10))


text:
Q: Is this splay tree incorrect in this UC Berkeley lecture video? https://youtu.be/G5QIXywcJlY?t=31m47s
At 31:47, I believe he performs a double right rotation with 5 being the grandparent, and 4 being the parent, and 1 being the child. After the double right rotation, he has 4 as the right child of 5.

A: No it is not. He first performs a RR pivot so that the 1 has the 2 and the 3 off to its right. He then performs the same RR pivot but this time 1 has a right child so that right child has to be put somewhere so that 5-4 can become the new right child. The solution is to make 5-4 the new right child and then put the old right child to the left of the 5.


text:
Q: Invalid context when rendering with CIContext I have a NSView that renders some CoreImage stuff in drawRect: method. Everything works fine while I'm rendering on hw-accelerated context, but if I switch to software mode, I have error messages in console for each render:
<Error>: CGBitmapContextGetBitsPerComponent: invalid context 0x1084740 This isn't a bitmap context. Forcing destination format to ARGB_8 for CGContext.
<Error>: CGBitmapContextGetBitsPerComponent: invalid context 0x1084740

Similar issue happens when I render Quartz composition to the CIContext of my NSView. I get a CIImage from QCRenderer and draw it in drawRect: method, however, I have an error each [CIContext drawImage:] call:
<Error>: unknown error code: invalid context

Despite of this error the actual rendering is successful and everything looks fine (visually). It looks like this issues happen when I'm rendering on screen, rendering to an offscreen bitmap context doesn't cause such issue.
Can anyone say how to avoid this issues while drawing on screen (except of using offscreen memory buffer to draw - it's to slow)?


text:
Q: Can't deploy Google Cloud Datalab - Application in non-US zone I've selected my Google API project 4 times now and pushed "Deploy DataLab", but whenever I check back I have no Datalab project.
The last time I had the following error message, but I have billing enabled, am the owner and the BigQuery/Google Compute Engine APIs are activated.

Checking the logs it says I'm in the wrong region:
Oct 13 19:42:35 datalab-deploy-main-20151013-19-40-34 startupscript: Pushing tag for rev [b886390e822d] on {https://gcr.io/v1/repositories/_m_sdk/mark-edmondson-gde.datalab.main/tags/latest}
Oct 13 19:42:36 datalab-deploy-main-20151013-19-40-34 startupscript: 07:42 PM Host: appengine.google.com
Oct 13 19:42:36 datalab-deploy-main-20151013-19-40-34 startupscript: 07:42 PM Application: mark-edmondson-gde (was: None); module: datalab; version: main (was: None)
Oct 13 19:42:36 datalab-deploy-main-20151013-19-40-34 startupscript: 07:42 PM
Oct 13 19:42:36 datalab-deploy-main-20151013-19-40-34 startupscript: Starting update of app: mark-edmondson-gde, module: datalab
Oct 13 19:42:36 datalab-deploy-main-20151013-19-40-34 startupscript: 07:42 PM Getting current resource limits.
Oct 13 19:42:36 datalab-deploy-main-20151013-19-40-34 startupscript: 07:42 PM Scanning files on local disk.
Oct 13 19:42:37 datalab-deploy-main-20151013-19-40-34 startupscript: Error 400: --- begin server output ---
Oct 13 19:42:37 datalab-deploy-main-20151013-19-40-34 startupscript: Managed VMs can not be hosted in the application's region.
Oct 13 19:42:37 datalab-deploy-main-20151013-19-40-34 startupscript: --- end server output ---
Oct 13 19:42:37 datalab-deploy-main-20151013-19-40-34 startupscript: ERROR: (gcloud.preview.app.deploy) Command failed with error code [1]
Oct 13 19:42:37 datalab-deploy-main-20151013-19-40-34 startupscript: Step deploy datalab module failed.

A: Currently managed VMs are in beta and only supported in the US.
Investigating if its possible to override the zone setting when deploying Datalab.

A: Unfortunately, at this point, cloud projects created with non-US (i.e. "europe-west") App Engine location do not allow managed VM deployment. There is no override available as of now to deploy to a US-based location where managed VMs are available. A workaround would be to create another project and grant access to relevant data to the App Engine service account.
Apologies for the inconvenience.


text:
Q: Details entered in windows form will not save to CSV file the information I enter in my form is not being stored in my CSV file. Just a blank file. the file name updates with todays date.
here is my code.
   private void btnSave_Click(object sender, EventArgs e)
    {

        string date = DateTime.Today.ToString("dd-MM-yyyy"); //get today's date
        string filePath = "Policy_" + date + ".csv";  //create a name of the new csv file (including the date)

        string delimiter = ","; //comma needed to create new csv file

        StringBuilder sb = new StringBuilder();
        foreach (DriverDetails driverDetails in driverDet) //go through the List called DriverDetails and examine each object in turn
        {
            sb.AppendLine(driverDetails.Title + delimiter + driverDetails.FName + delimiter + driverDetails.SName + delimiter + driverDetails.Dob + delimiter + driverDetails.Phone + delimiter + driverDetails.Email + delimiter + driverDetails.Employment + delimiter + driverDetails.Marital + delimiter + driverDetails.HouseNo + delimiter + driverDetails.Street + delimiter + driverDetails.Postcode + delimiter);//uild up a String containing all the data in the List
        }

        File.WriteAllText(filePath, sb.ToString());

        //File.AppendAllText(filePath, sb.ToString()); //add the new string (made up of SEVERAL lines, each representing data from ONE order) to the end of the csv file
        MessageBox.Show("Driver details saved to file");
    }

A: You can replace
File.WriteAllText(filePath, csv.ToString());

with
File.AppendAllText(filePath, csv.ToString());

A: I use the following code to fill the driverDet, and then can write the data to the csv file.
class DriverDetails
{
    public string Title { get; set; }
    public string FName { get; set; }
    public string SName { get; set; }
}

List<DriverDetails> driverDet = new List<DriverDetails> {
    new DriverDetails { Title = "T1", FName = "F1", SName = "S1"},
    new DriverDetails { Title = "T2", FName = "F2", SName = "S2"},
    new DriverDetails { Title = "T3", FName = "F3", SName = "S3"}};


text:
Q: Trigger/activate the RowEditor from bean for a primefaces In-Cell editing enabled p:dataTable I have a primefaces p:dataTable with InCell editing enabled and want to trigger/activate the RowEditor for the newly added row.
Excerpt of XHTML
<p:commandButton id="btnAddEntry" value="Add new row" actionListener="#{myBean.addNewCar}" ... update="carTable growl" process="@this carTable ..."/>

<p:dataTable id="carTable" var="car" value="#{myBean.cars}" ... editable="true">
        <p:column ...>
            <p:cellEditor>
                ...
            </p:cellEditor>
        </p:column>
    ...
        <p:column ...>
                <p:rowEditor />
        </p:column>
    ...
</p:dataTable>

Here is what i have so far for the bean method:
public void addNewCar() {

    Car newCar = new Car();
    cars.add(newCar);

    FacesContext facesContext = FacesContext.getCurrentInstance();
    UIComponent uiTable = ComponentUtils.findComponent(facesContext.getViewRoot(), "carTable");
    DataTable table = (DataTable) uiTable;

    final AjaxBehavior behavior = new AjaxBehavior();
    RowEditEvent rowEditEvent = new RowEditEvent(uiTable, behavior, table.getRowData());
    rowEditEvent.setPhaseId(PhaseId.UPDATE_MODEL_VALUES);
    table.broadcast(rowEditEvent);
}

i don't know

*

*if this is the correct approach

*in case yes, which object to pass to the constructor RowEditEvent(UIComponent component, Behavior behavior, Object object) as the 3rd parameter

A: I used the execute(..) method of class RequestContext in my create method. This allowed me to first calculate the index of the row to go into edit mode and to include it dynamically in the javascript:
RequestContext.getCurrentInstance().execute("jQuery('span.ui-icon-pencil').eq(" + rowToEditIndex + ").each(function(){jQuery(this).click()});");

Hope this helps.

A: If you have only one data table in the facelet try to use this
oncomplete="jQuery('.ui-datatable-data tr').last().find('span.ui-icon-pencil').each(function(){jQuery(this).click()});

Add this to the command button. This should work.

A: You can add an unique styleClass to the dataTable, and one javascript function in the commandButton:
So add to the table:
styleClass="myTable"

And to the button:
oncomplete="$('.myTable tbody.ui-datatable-data tr:last-child td span.ui-row-editor span.ui-icon-pencil').click()"

And your code will look like this:
<p:commandButton id="btnAddEntry" value="Add new row" actionListener="#{myBean.addNewCar}" ... update="carTable growl" process="@this carTable ..." oncomplete="$('.myTable tbody.ui-datatable-data tr:last-child td span.ui-row-editor span.ui-icon-pencil').click()"/>

<p:dataTable styleClass="myTable" id="carTable" var="car" value="#{myBean.cars}" ... editable="true">
        <p:column ...>
            <p:cellEditor>
                ...
            </p:cellEditor>
        </p:column>
    ...
        <p:column ...>
                <p:rowEditor />
        </p:column>
    ...
</p:dataTable>

A: This solution aims to resolve a few drawbacks of the original answer of:
oncomplete="jQuery('.ui-datatable-data tr').last().find('span.ui-icon-pencil').each(function(){jQuery(this).click()});"

The above statement retrieves all "tr" elements which are descendants (at any level) of elements with the ".ui-datatable-data" class.  The potential issues with that are:

*

*As mentioned by @Gnappuraz, if there are multiple p:datatable's in the document, this statement will choose the last table.

*Additionally, I ran into a problem where even with one datatable, a column with a p:selectOneRadio component will also render a html table (that contains "tr" elements).  In this case the selector chooses the last "tr" for the p:selectOneRadio's table, rather than the p:datatable.

*Not a problem, but the statement can be shortened to exclude the each() because of jQuery's implicit iteration.

What I ended up with was:
oncomplete="jQuery('#tableForm\\:table .ui-datatable-data > tr').last().find('span.ui-icon-pencil').click();"

This selector says - get the last "tr" element, which is a direct child of an element with class ".ui-datatable-data", which is also a descendant of the element with id "table" in form "tableForm".  In other words you can now have multiple p:datatables, and any include any components that render html tables.

A: Try this :
jQuery('#FormID\\:DataTableID\\:#{datatable.size()}\\:rowEditorID').find('span.ui-icon-pencil').each(function(){jQuery(this).click()});

worked well, no matter how many datatables in a same page.

A: If you have several DataTable which each of them has an ID, then try to use one of these solutions:
Oncomplete="jQuery('#FrmID:TabViewI:mydataTableID'.replace(/:/g,'\\:')).find('span.ui-icon-pencil').each(function(){jQuery(this).click()});"

OR:
oncomplete="jQuery('#FrmID\\:TabViewID\\:mydataTableID').find('span.ui-icon-pencil').each(function(){jQuery(this).click()});"

This should work perfectly.

A: Execute a JQuery script on complete process :
oncomplete="editNewRow()"

        <script type="text/javascript">
            $(document).on("keydown", ".ui-cell-editor-input input", function(event) {
                if (event.keyCode == 13) {
                    $(this).closest("tr").find(".td-edition .ui-row-editor .ui-row-editor-check .ui-icon-check").click();
                    return false;
                }
            });

            function editNewRow() {
                $("#pim\\:invoiceRuleCretariaTable tbody:first tr:first .td-edition .ui-row-editor .ui-icon-pencil").click();
            }
        </script>

The first function submit the addition action by press on "Enter" key

A: Execute a JQuery script on complete process :
oncomplete="editNewRow()"

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script type="text/javascript">
            $(document).on("keydown", ".ui-cell-editor-input input", function(event) {
                if (event.keyCode == 13) {
                    $(this).closest("tr").find(".td-edition .ui-row-editor .ui-row-editor-check .ui-icon-check").click();
                    return false;
                }
            });

            function editNewRow() {
                $("#panel\\:carTable tbody:first tr:last .td-edition .ui-row-editor .ui-icon-pencil").click();
            }
        </script>

The first function submit the addition action by press on "Enter" key

A: To solve this is better to use styleClass and because for fix this it is necessary to use javascript, you need to check the html tags in your browser, because it seems that they change with the versions of primefaces. For vesion 6.1 I've put this on my bean:
RequestContext requestContext = RequestContext.getCurrentInstance();
requestContext.execute("$('.styleEventosPlanPrestacion tbody.ui-datatable-data tr:first-child td div.ui-row-editor a.ui-row-editor-pencil').click()");

and In my .xhtml I've  put this:
<p:dataTable ... styleClass="styleEventosPlanPrestacion">


text:
Q: Preciso desenvolver um programa que dado um arquivo de entrada, gere um arquivo de saída em java Dado um arquivo de entrada, gere um arquivo de saída como mostrado abaixo
Arquivo de Entrada  |  Arquivo de Saida
--------------------+--------------------
1                   |  impar
2                   |  par
3                   |  impar
4                   |  par
5                   |  impar
6                   |  par

Consegui apenas ler o arquivo txt e separar os pares dos impares
queria saber como criar o arquivo de saída com o impar par, impar etc sem ter que separá-los
import java.io.BufferedReader;
import java.io.FileReader;

public class Questao1
{
    public static void main(String [] args) {

        try
        {
            FileReader arquivo = new FileReader("Entrada1.txt");
            BufferedReader leitor = new BufferedReader(arquivo);

            String linha = leitor.readLine();
            String pares = "";
            String impares = "";
            while (linha != null)
            {
                int numero = Integer.parseInt(linha);
                if (numero % 2 == 0){
                   pares += numero + "\n";
                } else{
                    impares += numero + "\n";
                }

            linha = leitor.readLine();
             }
            leitor.close();
                System.out.println(pares);
                System.out.println(impares);
        }

        catch (Exception ex) {
            System.err.print(ex.getMessage());
        }
    }
}

A: Fiz aqui uma implementação, o programa vai ler o arquivo, analisar e converter os dados e escrever o arquivo com a formatação indicada na sua pergunta.
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.FileReader;
import java.io.FileWriter;
import java.util.ArrayList;
import java.util.List;

public class Main {
    public static void main(String[] args) {
        // Os arquivos de entrada e saida.
        String inputFilename = "input.txt";
        String outputFilename = "output.txt";

        // Lista de entrada.
        List<String> lines = new ArrayList<>();

        // Abre o arquivo de entrada.
        try (BufferedReader buffer = new BufferedReader(new FileReader(inputFilename))) {
            String line;
            // Ler linha por linha.
            while ((line = buffer.readLine()) != null) {
                // Adiciona cada linha na lista lines.
                lines.add(line);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }

        // Lista de saida.
        List<String> outputLines = new ArrayList<>();

        // Ler cada item da lista lines.
        for (String line : lines) {
            // Converte o item para int.
            int numberInLine = Integer.parseInt(line);

            // Verifica se numberInLine é par ou impar e atribui o resultado a data.
            String data = numberInLine % 2 == 0 ? "par" : "impar";

            // Adiciona data na lista de saida.
            outputLines.add(data);
        }

        // Abre o arquivo de saida.
        try (BufferedWriter buffer = new BufferedWriter(new FileWriter(outputFilename))) {
            buffer.write("Arquivo de Entrada  |  Arquivo de Saida  ");
            buffer.newLine();

            buffer.write("--------------------+--------------------");
            buffer.newLine();

            // Faz um loop na lista lines.
            for (int i = 0; i < lines.size(); i++) {
                // Escreve cada item na lista lines e outputLines com uma formatação de espaços em branco.
                buffer.write(String.format("%-20s|  %-18s", lines.get(i), outputLines.get(i)));
                // Adiciona uma nova quebra de linha.
                buffer.newLine();
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

Exemplo
Arquivo de entrada:
0
1
2
3
4
5
6
7
8
9

Arquivo de saída:
Arquivo de Entrada  |  Arquivo de Saida
--------------------+--------------------
0                   |  par
1                   |  impar
2                   |  par
3                   |  impar
4                   |  par
5                   |  impar
6                   |  par
7                   |  impar
8                   |  par
9                   |  impar


text:
Q: AbstractMethodError thrown at runtime with java.sql.Connection I'm trying to work through creating a very simple class to send queries to an instance of Oracle XE 11g, essentially making a very simple SQL*Plus to get the basics of JDBC down.
The source code I'm currently working with is:
public class Example {
    static String username, password;
    static String dbDriver = "oracle.jdbc.driver.OracleDriver";
    static String dbConnection = "jdbc:oracle:thin:@//localhost:1521/xe";

    public static void main(String[] args) {
        Scanner input = new Scanner(System.in);
        String line;
        Connection c = null;
        Statement stmt = null;
        int loginAttempts = 0;

        // Log in loop
        do {
            try {
                Class.forName(dbDriver);
                System.out.print("Enter username: ");
                line = input.nextLine();
                if (line.contains("/")) {
                    String[] login = line.split("/");
                    if (login.length != 2) {
                        System.out
                                .println("Unrecognized information, exiting...");
                        System.exit(0);
                    }

                    username = login[0].trim();
                    password = login[1].trim();
                } else {
                    username = line;
                    System.out.print("Enter password: ");
                    password = input.nextLine();
                }

                c = DriverManager.getConnection(dbConnection, username,
                        password);
                stmt = c.createStatement();
                loginAttempts = -1;
            } catch (ClassNotFoundException e) {
                System.err.println("Unable to connect to database, exiting...");
                System.exit(-1);
            } catch (SQLException e) {
                System.out.println("Username and/or password is incorrect");
                if (++loginAttempts == 1) {
                    System.out.println("Too many failed login attempts, exiting...");
                    System.exit(0);
                }
            }
        } while (loginAttempts != -1);

        // Input loop
        for (;;) {
            try {
                // Write out the prompt text and wait for input
                if(c == null) {
                    throw new IllegalStateException("Connection should not be null");
                }
                System.out.print(c.getSchema() + ":> ");
                String tmp = input.nextLine();

                // Check if the user entered "exit"
                if (tmp.toLowerCase().equals("exit")) {
                    System.out.println("Exiting...");
                    input.close();
                    System.exit(0);
                }

                String query;
                // TODO: For some reason, no semi-colon is allowed
                if (tmp.charAt(tmp.length() - 1) == ';')
                    query = tmp.split(";")[0];
                else
                    query = tmp;
                // System.out.println(query);
                ResultSet rset = stmt.executeQuery(query);
                ResultSetMetaData rmd = rset.getMetaData();
                int colCount = rmd.getColumnCount();

                // Column indices start with 1, print column names
                for (int i = 1; i <= colCount; i++) {
                    System.out.printf("%-20.20s   ", rmd.getColumnName(i));
                }
                System.out.println();

                while (rset.next()) {
                    for (int i = 0; i < colCount; i++) {
                        System.out.printf("%-20.20s | ", rset.getString(i + 1));
                    }
                    System.out.println();
                }
                System.out.println();
            } catch (SQLSyntaxErrorException e) {
                System.out.println("Encountered a syntax error:\n"
                        + e.getMessage());
            } catch (SQLException e) {
                System.err.println("An unexpected error occurred");
                e.printStackTrace();
                input.close();
                System.exit(-1);
            }
        }

    }
}

In the second try/catch block, in the for(;;) loop, I get the following output:
Enter username: hr/hr
Exception in thread "main" java.lang.AbstractMethodError: oracle.jdbc.driver.T4CConnection.getSchema()Ljava/lang/String;
at jdbctest.Example.main(Example.java:69)

I checked out the Oracle docs (java.lang.AbstractMethodError), and it says that this error can only be thrown if:
"the definition of some class has incompatibly changed since the currently executing method was last compiled."
I'm thinking that there's something I'm missing with line 27, but I'm not sure how to approach this problem and any guidance would be extremely helpful.

A: I believe that your problem is due to the fact that you use a JDBC driver for a version of Java <= 6 and you use Java 7 or higher because the method Connection#getSchema() has been added in Java 7.
Use the latest version of your JDBC driver to avoid such issue or at least a JDBC driver compatible with your version of Java.

A: This works on DB2 (and an old version of the driver)
Connection.getMetaData().getConnection().getSchema();


text:
Q: install vmware tools in zeroshell 2.0 Situation
I'm using the 2.0 RC2 iso from http://www.zeroshell.org in a VMware ESXi 5.1 virtual machine and am trying to adapt the instructions on HowTo: vmware-tools in ZeroShell for v2.0 as the file layout is a little different.
Initial Deviation from Instructions
The instructions work successfully up to the line to unlink /cdrom/modules and re-link to /Database/rootfs/modules.  If you try and work around that by doing the same to the entire /lib folder it won't run any more programs.
Among other things, I believe vmtools needs to modify the content of the /lib/modules directory but in zeroshell, by default, this is stored and run from the CD.  I can't change the link for /lib/modules yet because the entire /lib is a symbolic link to /cdrom/lib and is read only.  So I'm trying to move /lib to the hdd by running the following but it has errors when running the ln command after unlinking /lib. This breaks everything and I restore from a snapshot to try again.
mkdir /Database/rootfs/lib
cp -a /lib/* /Database/rootfs/lib
unlink /lib && ln -s /Database/rootfs/lib /lib

To get ln work to work on that last line I tried changing it to be "ln -sfn /Database/rootfs/lib /lib"
any ideas on how to install vmware-tools in this VM? I've tried the .img.gz file from their download page and it just has a /dev/sda1 = /boot and /dev/sda2 = an iso9660 CD image and /dev/sda3 has profile storage, which results in the same problem of having to move /lib.
Extra System Info
After extracting the vmtools tar.gz file and before running the rest of the procedure, the system looks like
cat /etc/fstab
tmpfs      /            tmpfs      defaults        1     1
/dev/cdrom              /cdrom              iso9660 ro,remount 0 0
proc          /proc        proc     defaults        0     0
none          /sys         sysfs     remount        0     0
devpts        /dev/pts     devpts   gid=4,mode=620  0     0
shm           /dev/shm     tmpfs    defaults        0     0
usbfs       /proc/bus/usb  usbfs    defaults    0     0

cat /etc/mtab
tmpfs / tmpfs rw 0 0
proc /proc proc rw 0 0
/dev/sr0 /cdrom iso9660 ro 0 0
none /sys sysfs rw 0 0
devpts /dev/pts devpts rw,gid=4,mode=620 0 0
shm /dev/shm tmpfs rw 0 0
usbfs /proc/bus/usb usbfs rw 0 0
/dev/sda1 /DB ext4 rw,noatime 0 0
/DB/_DB.001 /Database none rw,bind,noatime 0 0

ls -al / | grep ">"
lrwxrwxrwx    1 root     root           10 Nov 21  2012 bin -> /cdrom/bin
lrwxrwxrwx    1 root     root           10 Nov 21  2012 lib -> /cdrom/lib
lrwxrwxrwx    1 root     root           21 Jul  4 02:57 sbin -> /cdrom/sbin
lrwxrwxrwx    1 root     root           20 Jul  4 02:57 usr -> /cdrom/usr

ls -l /lib/modules
lr-xr-xr-x    1 root     root           14 Nov 21  2012 /lib/modules -> /cdrom/modules

Current Problems
When running "./vmware-install.pl" it complains that it cannot find gcc or the kernel headers, and hence cannot compile modules.  I'm particularly after the VMCI module and the memory module would be handy aswell.  The distro already comes with a vmxnet3 driver and paravirtual disk controller driver so I don't need to compile those.
With the below instructions it looks like it is running fine, but if I try and use the viClient to shutdown or restart the VM it gives me the error: "The request to Reset this virtual machine failed because the corresponding VMware Tools script did not run successfully. If you have configured a custom reset script in this virtual machine, make sure that it contains no errors."
when I go to the shell and try and run what I think is the command to shutdown it says
/etc/vmware-tools/poweroff-vm-default poweroff-vm /etc/vmware-tools
Thu Jul 4 09:29:44 CEST 2013 : Executing '/etc/vmware-tools/poweroff-vm-default'
Thu Jul 4 09:29:44 CEST 2013 : Executing '/etc/vmware-tools/scripts/vmware/network'

Jul 04 09:29:44 network: ifup not in search path.

Current Method to Install VMtools
Ensure that the linux.iso file is connected to cd2 and then paste the following code in to the console

mkdir /mnt/cd2
chmod 555 /mnt/cd2
mount -t auto /dev/sr1 /mnt/cd2
cp /mnt/cd2/VMwareTools*.tar.gz /Database
cd /Database
tar -xvzf VMwareTools*.tar.gz
rm -f VMwareTools*.tar.gz
umount /dev/sr1

cd /Database
mkdir rootfs
cd rootfs
mkdir sbin
mkdir usr
cp -a /sbin/* /Database/rootfs/sbin
cp -a /usr/* /Database/rootfs/usr

mount -o remount,rw /
unlink /sbin && ln -s /Database/rootfs/sbin /sbin
unlink /usr && /cdrom/usr/bin/ln -s /Database/rootfs/usr /usr

mkdir /Database/rootfs/lib
cp -a /lib/* /Database/rootfs/lib
rm -f /Database/rootfs/lib/modules
cp -a /cdrom/modules /Database/rootfs/lib/modules
cd /Database/rootfs/lib

ln -sfn /Database/rootfs/lib /lib

mkdir /Database/vmware-tools
cd /Database/vmware-tools
mkdir etc
cd etc
mkdir init.d
mkdir rc.d
cd rc.d
mkdir rc0.d
mkdir rc1.d
mkdir rc2.d
mkdir rc3.d
mkdir rc4.d
mkdir rc5.d
mkdir rc6.d

cd /Database/vmware-tools-distrib
./vmware-install.pl

ensure the paths all start with ''/Database/vmware-tools/'' and when manually typing ensure that they end with a trailing /
Then you're ready to configure.  Say no to everything, it complains about not being able to find gcc or kernel headers and hence cannot compile modules like the vmci module to allow communication with the host for commands like shutdown guest.  <---- This is a problem

cd /Database/vmware-tools/usr/bin
./vmware-config-tools.pl

VMtools will currently be running, but to ensure that it starts with the machine paste in the below
cd /Database/vmware-tools
mkdir startup
mkdir startup/etc
mkdir startup/etc/vmware-tools
cp -a /etc/vmware-tools/* /Database/vmware-tools/startup/etc/vmware-tools

cat <<EOF > /Database/vmware-tools/startup/run.sh
#!/bin/bash
mount -o remount,rw /

unlink /usr && /cdrom/usr/bin/ln -s /Database/rootfs/usr /usr
unlink /sbin && ln -s /Database/rootfs/sbin /sbin
ln -sfn /Database/rootfs/lib /lib

cp -a /Database/vmware-tools/startup/etc/* /etc

/Database/vmware-tools/etc/rc.d/vmware-tools start
EOF
chmod 766 /Database/vmware-tools/startup/run.sh

Now WebLogin into ZeroShell. Go to the panel "Startup/Cron", select "post boot", enable status, and add the following line:  ''/Database/vmware-tools/startup/run.sh''

A: I would suggest trying bind mounts (like /Database already is) rather than the unlink/relink games that page has you play.
Try something like /Database/rootfs/lib/modules   /lib/modules   none   rw,bind   0 0 in /etc/fstab for /lib/modules.
Alternatively, I assume your problem replacing the /lib symlink was that commands started to fail immediately after the /lib symlink was removed. That's likely because the replacement was not atomic. You might have better luck with ln -sfT /Database/rootfs/lib /lib as that should be more atomic if not, in fact, actually atomic (I don't know offhand).


text:
Q: 'git diff' documentation refers to 'source' and 'destination' but doesn't say which corresponds to index The documentation for 'git diff' refers to 'source' files (default output prefix is 'a/') and 'destination' files (default output prefix is 'b/'). My question is, does 'source' refer to the file(s) in the index (staging area) and 'destination' the file(s) in the work directory, or is it the other way around?

A: The answer to that is both no and yes.1
git diff can compare things to your staging area, but it doesn't always do that. Let's consider these common cases:

*

*git diff, with no additional arguments.  This means "compare the tree associated with the index against the tree in the current working directory."  In this case, "source" is the index.

*git diff HEAD, with no additional arguments.  This means "compare the tree in HEAD against the tree in the working directory."  In this case, the index is not used at all.  The same is true if you name a specific revision or branch.

*git diff --cached, with no additional arguments.  This means "compare the tree in HEAD against the tree in the index."  In this case, "destination" is the index.

*git diff --cached <rev>: this is the same as #3 but using the specified revision as the source.

*git diff <rev1> <rev2>: this compares the trees of the two specified revisions, ignoring both the index and the work-tree.
Thus, sometimes the staging area is either the source or the destination, and sometimes it is not used at all.

It is said: go not to the Elves for answers, for they will say both no and yes.

A: Never mind. Source is index, destination is work. All I had to do was look at the work file. D'oh! Total brain fart.


text:
Q: npgsql : Selecting a null data throws exception with error "Column is Null" I am running npgsql v3.7 with .NetCore on Ubuntu.
When I execute a select query and a cell in any row in the results is null, an exception is thrown with the error message "Column is null".
I am having to work around this by putting every column in the select clause inside a case statement which tests for NULL
"CASE WHEN " + fieldName + " IS NULL THEN '' ELSE " + fieldName + " END "

This seems a bit extreme and should not be necessary.  Has anyone else come across this.
Thanks.

A: You are probably trying to read the column like this:
using (var reader = cmd.ExecuteReader()) {
  reader.Next();
  var o = reader.GetString(0);   // Or any other of the Get methods on reader
  ...
}

This code will fail if the column contains a null, and is the expected behavior. In ADO.NET, you need to check for a null value with reader.IsDBNull(0) before actually getting the value. That's just how the database API works.

A: I don't know why NULL values are giving you errors, but you can do away with the ugly CASE statement in favor of using COALESCE:
"COALESCE(" + fieldName + ", '')"

Ideally you should make a configuration change such that NULL values do not cause this problem.


text:
Q: Does the finalization routine need to be elemental in order to be called on the elements of allocatable array that goes out of scope? If I have an allocatable array of a finalizable derived type, will the finalizer be called on every individual element when the array goes out of scope?
Here is a small code example that illustrates the question:
module LeakyTypeModule

   implicit none
   private

   type, public :: LeakyType
      real, pointer :: dontLeakMe(:) => null()
   contains
      procedure :: New
      final     :: Finalizer
   end type

contains

   subroutine New(self, n)
      class(LeakyType), intent(out) :: self
      integer         , intent(in)  :: n
      allocate(self%dontLeakMe(n))
      self%dontLeakMe = 42.0
   end subroutine

   subroutine Finalizer(self)
      type(LeakyType), intent(inout) :: self
      if (associated(self%dontLeakMe)) deallocate(self%dontLeakMe)
   end subroutine

end module

program leak

   use LeakyTypeModule
   implicit none

   type(LeakyType), allocatable :: arr(:)

   allocate(arr(1))
   call arr(1)%New(1000)
   deallocate(arr)

end program

Note that this program leaks the dontLeakMe array allocated in the New() method of LeakyType. At first this was a bit surprising for me but, then I discovered that the problem can be fixed by declaring the finalizer elemental. Both gfortran and ifort behave in the same way, so I assume this behaviour is following the Fortran 2003 standard.
Can anyone confirm this? To be honest I have a hard time time understanding what the standard says on this particular point.
Right now I also can't see much use in not declaring all my finalizers elemental. Does this have any application I'm overlooking?

A: The rules for determining whether a final procedure is invoked, and which final procedure is invoked, are the same as for resolution of generic procedures in terms of rank matching requirements.
Noting that the question is tagged Fortran 2003...
Elemental procedures in Fortran 2003 and prior have to be PURE.  If your finalizer needs to do something that is incompatible with the pure attribute (which is reasonably common) then the finalizer cannot be elemental, and you need to write the rank specific variants.
Fortran 2008 introduces the concept of IMPURE ELEMENTAL, which is quite handy for writing finalizers.


text:
Q: $n-$dimension integral Is there anyone could help me solve the following equation:
$$\int_0^t \int_0^{t-v_1} \cdots \int_0^{t-\sum_{i=1}^{k-1} v_i} \prod_{j=1}^k f(\sum_{i=1}^{j} v_i) dm(v_k) \cdots dm(v_2)dm(v_1)$$
You may safely assume $f(v), m(v)$ are nice functions here. I am only interested how to solve this kind of integral and what kind of m could enable us to achieve a nice result.


text:
Q: Next.js, loading a library client side, the component is re rendered twice and multiple times as the parent component state changes I'm loading this library emoji-mart client side because it requires window object and then returning a component, while calling, the component is rendered twice to start with and then multiple times as parent component state changes.
function EmojiPicker(props = {}) {
  const ref = useRef()

  // loading the emojiMart lib clientside coz it requires
  // window object
  useEffect(() => {
    import('emoji-mart').then((EmojiMart) => {
      new EmojiMart.Picker({ ...props, data, ref })
    })
  }, [])

  return

}

function Feed = () => {

  const[value, setValue] = useState('')

  return (
  ...
  ...
  <input value={value} onChange={handleChange}/>
  ...
  ...

  <EmojiPicker/>
  /* EmojiPicker rendered twice and again and again whenever
  input state changes */

  )
}

A: You can use React.memo to prevent unnecessary rerendering.
It's easy to use, only you have to do is to wrap the component.
import React from 'react';

const EmojiPicker = React.memo(() => {
 ...
 return

})

React.memo prevent rerender if there's no changes in props variables.


text:
Q: Does a filename in Ubuntu starting with "readme" automatically become a readme document type? I'm working on a tomcat project so I saved a jsp file with the name of readmessages.jsp with sublime-text editor.
When I opened and saw its type (because it was displaying a readme icon on top of the jsp file), it was - README document (text/x-readme). I even tried saving it with Gedit and Atom but all in vain.
But then I changed the filename and it just worked out! I renamed the file from readmessages.jsp to temp.jsp and checked its file type. It was - HTML document.
I don't think it's because of the code typos in that jsp file because the same results were given back from other files too.
Please explain why files starting with "readme" (as in, readmessages.jsp) become README document (text/x-readme) automatically in Ubuntu.
Is there a fix or workaround for saving files with different file type if they have a "readme" phrase in them? Thanks in advance!

A: html and scripts are also plain text so the file type hasn't changed, just weird mojo about subclass icon decisions,
I found something that may help you:
Save the following as jsp.xml:
<?xml version="1.0" encoding="UTF-8"?>
<mime-info xmlns='http://www.freedesktop.org/standards/shared-mime-info'>
  <mime-type type="text/x-jsp">
    <comment>JSP file</comment>
    <glob pattern="*.jsp"/>
  </mime-type>
</mime-info>

Then open a terminal and run
xdg-mime install --novendor jsp.xml

Now all files with the extension .jsp should have the MIME type text/x-jsp.
See Shared MIME-info Database if you want to learn more about how MIME types are defined.


text:
Q: convert the columns into Horizontal PIVOT I have 3 column file with ID,name and value .
1,Brand,sports
1,Color,White
1,Gender,Male
1,Logo,yes
1,width,10
4,Brand,Running
4,width,12
4,Fits,Lose
3,catgegory,shoe
3,Color,blue
3,Color,white
3,primarycolor,blue
5,size,M
5,Brand,Sports
5,Brand,Running

I'm trying to convert this into a horizontal format based on the column 1 and column 2.
It's similar to the Pivot table with text values printed, it can't be done using Excel pivot it will allow only sum/count of values.
Can this be generated in UNIX?
,Brand,Color,Gender,Logo,width,Fits,catgegory,primarycolor,size
1,sports,White,Male,yes,10,,,,
4,Running,,,,12,Lose,,,
3,,blue/white,,,,,shoe,blue,
5,Sports/Running,,,,,,,,M

A: Input
akshay@db-3325:/tmp$ cat data.txt
1,Brand,sports
1,Color,White
1,Gender,Male
1,Logo,yes
1,width,10
4,Brand,Running
4,width,12
4,Fits,Lose
3,catgegory,shoe
3,Color,blue
3,primarycolor,blue
5,size,M
5,Brand,Running

Script
akshay@db-3325:/tmp$ cat pivot.awk
{
     id=$1; name=$2; value=$3
     ids[id];
     # this is to retain order
     if(!(name in tmp)){ tmp[name]; names[++c]=name; }
     values[id,name] = value
}
END {
     # comment below line if you hide "id"
     printf "id"

     for (name in names) {
         printf "%s%s",OFS,names[name]
     }
     print ""
     for (id in ids) {
         printf "%s",id
         for (name in names) {
             printf "%s%s",OFS,values[id,names[name]]
         } print ""
     }
}

Execution and Output
akshay@db-3325:/tmp$ awk -v FS=, -v OFS=, -f pivot.awk data.txt
id,Brand,Color,Gender,Logo,width,Fits,catgegory,primarycolor,size
1,sports,White,Male,yes,10,,,,
3,,blue,,,,,shoe,blue,
4,Running,,,,12,Lose,,,
5,Running,,,,,,,,M

This produces o/p same as expected o/p including order
akshay@db-3325:/tmp$ cat pivot_with_order.awk
{
     id=$1; name=$2; value=$3

     # this is to retain order
     if(!(id in itmp)){ itmp[id]; ids[++i]=id; }
     if(!(name in tmp)){ tmp[name]; names[++c]=name; }

     values[id,name] = value
}
END {
     # uncomment below line if you want to display "id"
     # printf "id"

     for (name in names) {
         printf "%s%s",OFS,names[name]
     }
     print ""
     for (id in ids) {
         printf "%s",ids[id]
         for (name in names) {
             printf "%s%s",OFS,values[ids[id],names[name]]
         } print ""
     }
}

Output
akshay@db-3325:/tmp$ awk -v FS=, -v OFS=, -f pivot_with_order.awk data.txt
,Brand,Color,Gender,Logo,width,Fits,catgegory,primarycolor,size
1,sports,White,Male,yes,10,,,,
4,Running,,,,12,Lose,,,
3,,blue,,,,,shoe,blue,
5,Running,,,,,,,,M

A: Excel VBA:
Sub Pivot()

    Dim rngData, rngOut, r, c, dR, dC
    Set dR = CreateObject("scripting.dictionary")
    Set dC = CreateObject("scripting.dictionary")

    Set rngData = ActiveSheet.Range("A2:C2") '<< first row of input
    Set rngOut = ActiveSheet.Range("G2")     '<< where to put output

    Do While Application.CountA(rngData) > 0
        r = rngData(1)
        c = rngData(2)
        If Not dR.exists(r) Then
            dR.Add r, dR.Count + 1
            rngOut.Offset(dR.Count, 0) = r
        End If
        If Not dC.exists(c) Then
            dC.Add c, dC.Count + 1
            rngOut.Offset(0, dC.Count) = c
        End If

        With rngOut.Offset(dR(r), dC(c))
            'if already has a value, add a newline separator
            .Value = .Value & IIf(.Value <> "", vbLf, "") & rngData(3)
        End With
        Set rngData = rngData.Offset(1, 0)
    Loop

End Sub

A: Python 2.7
Assuming that list.csv is:
1,Brand,sports
1,Color,White
1,Gender,Male
1,Logo,yes
1,width,10
4,Brand,Running
4,width,12
4,Fits,Lose
3,catgegory,shoe
3,Color,blue
3,Color,white
3,primarycolor,blue
5,size,M
5,Brand,Sports
5,Brand,Running

Python code in un.py:
# up.py
#
import csv
rowid={};  colid={};  tab={};  rowTitle=[];  colTitle=[]
with open('list.csv', 'rb') as csvfile:
  v = csv.reader(csvfile)
  for row in v:
    rowid[row[0]]=1;  colid[row[1]]=1;  k=row[0]+"@"+row[1]
    if tab.has_key(k):
      tab[k]=tab[k]+"/"+row[2]
    else:
      tab[k]=row[2]

rowTitle=rowid.keys(); colTitle=colid.keys()
rowTitle.sort();  colTitle.sort();

s=""
for j in colTitle: s=s+","+j
print s
for i in rowTitle:
  s=i
  for j in colTitle:
    k=i+"@"+j
    s=s+","
    if tab.has_key(k):
      s=s+tab[k]
  print s

py un.py output is:
,Brand,Color,Fits,Gender,Logo,catgegory,primarycolor,size,width
1,sports,White,,Male,yes,,,,10
3,,blue/white,,,,shoe,blue,,
4,Running,,Lose,,,,,,12
5,Sports/Running,,,,,,,M,