text:
Q: Form which generates image in real-time I am looking to build a form which updates an image in real-time.
Could someone help me out and tell me the best way to go about creating a form similar to this (languages, techniques, etc): http://www.demonplates.com/platebuilder.php
Where as you enter details the image is updated accordingly. The form will send to google checkout with the data entered.
Much appreciated.

A: You don't even have to use AJAX for this. Assuming the script generating the image takes a GET parameter such as: generate_image.php?text=foo
You can just dynamically update the src attribute of the image every time the contents of the input box change. Here's an example using jQuery.
<input type="text" id="image_text" value="your text here" />

And the JavaScript:
$('#image_text').change(function() {
    $('#generated_image').attr('src', $(this).val());
});


text:
Q: squish startApplication() won't start an application with space I have an application with a space in the name of the application. Is it possible to start the application using squish's startApplication() function?

A: Please refer to the link below. Squish documentation refers to many possible way to connect to an AUT. You can map your application on the AUT settings and call the application without space while running your test case.
Reference Link: https://doc.froglogic.com/squish/latest/rg-autsettings.html

A: When the application/binary name contains a space please enclose it in double quotes, startApplication('"my aut name"').

redpajama_set_name: RedPajamaStackExchange


text:
Q: I am having trouble with streamreader in c# I am having a little trouble with the streamreader.
I am opening emails from the file dialog, and those emails are placed inside a listbox.
each letter in the emails, are on one line, as shown in the picture below.
I want the emails to be on one line, can some one help me, this is giving me a headache.
private void button2_Click(object sender, EventArgs e)
{
    OpenFileDialog ofg = new OpenFileDialog();
    ofg.Filter = "Text Files|*.txt";
    if (ofg.ShowDialog() == System.Windows.Forms.DialogResult.OK)
    {
        var fileName = ofg.FileName;

        StreamReader sr = new StreamReader(File.OpenRead(fileName));
        var line = sr.ReadToEnd();

        foreach (var l in line)
            listBox1.Items.Add(l.ToString());

        sr.Dispose();
    }
}

A:         var lines = File.ReadAllLines( fileName );

        foreach (var l in lines )
        {
            listBox1.Items.Add( l );
        }

assuming that you have
        email1@email1.com
        email2@email2.com

in your file (this is what I understood from your description).

A: use this:
string line;
while((line = reader.ReadLine()) != null)
    listBox1.Items.Add(line);

A: Use it as follow:

using (StreamReader sr = new StreamReader(File.OpenRead(fileName)))
{
      string line;

      while ((line = sr.ReadLine()) != null)
      {
          listBox1.Items.Add(line.ToString());
      }
}

This reads all the lines in the file and adds it to the listbox line by line.

A: string containl chars, so foreach (var l ...) iterates through chars in line.
You should replace your foreach with
foreach( var email in line.Split(' '))

In case your emails separated with spaces.
Another approach would be File.ReadAllLines, in case emails in your file is on separate lines...

A: using (StreamReader sr = new StreamReader(File.OpenRead(fileName)))
{
   while (sr.Peek() >= 0)
   {
      listBox1.Items.Add(sr.ReadLine());
   }
}

Reference: http://msdn.microsoft.com/en-us/library/system.io.streamreader.readline


text:
Q: How to connect frontend and backend Linux servers using cable? I'm trying to connect a web server A, with a database server B so that they have the least possible delay. Both servers run Debian, are on the same rack and are connected together by a cable on their second Ethernet port . here are the /etc/network/interfaces specs.
Server A (front)
auto lo
iface lo inet loopback

# The primary network interface
allow-hotplug eth0
iface eth0 inet static
        address 11.22.33.5
        netmask 255.255.255.248
        network 11.22.33.3
        broadcast 11.22.33.10
        gateway 11.22.33.4
        # dns-* options are implemented by the resolvconf package, if installed
        dns-nameservers 8.8.8.8

Server B (back)
auto lo
iface lo inet loopback
auto eth0

# The primary network interface
allow-hotplug eth0
iface eth0 inet static
        address 11.22.77.8
        netmask 255.255.255.248
        network 11.22.77.6
        broadcast 11.22.77.23
        gateway 11.22.77.7
        # dns-* options are implemented by the resolvconf package, if installed
        dns-nameservers 11.22.77.89

I am wondering what change(s) should I make to the interface files in order to make server A communicated directly with B through the cable.  Thanks

A: Make sure the IP-addresses are on the same IP-network. In the config-snips you gave, they aren't.
So a valid configuration would be:
# Server A
iface eth0 inet static
        address 11.22.33.1
        netmask 255.255.255.248
        network 11.22.33.0
        broadcast 11.22.33.7

# Server B
iface eth0 inet static
        address 11.22.33.2
        netmask 255.255.255.248
        network 11.22.33.0
        broadcast 11.22.33.7

Learn about how IP-networks, their sizes and how netmasks work. The config-snips you gave make no sense at all. network 11.22.33.3 is no network (networks always start with even numbers) and 11.22.77.23
 is not the broadcast address of the network 11.22.77.6 with the netmask of 255.255.255.248.

A: Neither should have a gateway set, since there is no routing going on. Configure both interfaces to be on the same subnet. Then create a persistent static route on both machines that point to each other and is bound to the second interface. man route should help you with this part if you're unsure of how to do it.


text:
Q: Set Output parameter to rowcount I have the following procedure
create procedure hozzaszolas
  @pHozzaszolasSzam int
  , @pmcsz int output
as
begin
  update Cikkek
    set Ertekeles = Ertekeles + 1
  where Cikkek.CikkCim in (
    select Cikkek.CikkCim
    from Cikkek
    left join Hozzaszolasok on Cikkek.CikkID = Hozzaszolasok.CikkID
    where Cikkek.Ertekeles < 10
    group by Cikkek.CikkID, Cikkek.CikkCim
    having count(Hozzaszolasok.CikkID) >= @pHozzaszolasSzam
  )
end

I would like to get the number of rows affected in the output param, but I don't know how.

A: @@ROWCOUNT returns the number of records affected by the last statement.
create procedure hozzaszolas
  @pHozzaszolasSzam int
  , @pmcsz int output
as
begin
  update Cikkek
    set Ertekeles = Ertekeles + 1
  where Cikkek.CikkCim in (
    select Cikkek.CikkCim
    from Cikkek
    left join Hozzaszolasok on Cikkek.CikkID = Hozzaszolasok.CikkID
    where Cikkek.Ertekeles < 10
    group by Cikkek.CikkID, Cikkek.CikkCim
    having count(Hozzaszolasok.CikkID) >= @pHozzaszolasSzam
  )
set @pmcsz= @@ROWCOUNT
end


text:
Q: Can not add a list in document object using iTextSharp  public ActionResult PartTimeFacultyCourseLoadReport()
    {
        var teacherStatistics = (from t in db.Teachers
                                 join c in db.Courses
                                     on t.Id equals c.TeacherId into cGroup
                                 where t.Status == "Part Time"
                                 orderby t.Designation descending
                                 select new
                                 {
                                     TeacherInfo = t,
                                     CourseInfo = from cg in cGroup
                                                  orderby cg.Code ascending
                                                  select cg
                                 }).ToList();

        List<TeacherStatistics> teacherStatisticses = new List<TeacherStatistics>();

        int count = 0;
        foreach (var teacherStatistic in teacherStatistics)
        {
            TeacherStatistics aTeacherStatistics = new TeacherStatistics();
            aTeacherStatistics.Name = teacherStatistic.TeacherInfo.Name;
            aTeacherStatistics.Designation = teacherStatistic.TeacherInfo.Designation;
            aTeacherStatistics.NumberOfCourse = teacherStatistic.TeacherInfo.NumberOfCourse;
            count = 0;
            foreach (var courseInfo in teacherStatistic.CourseInfo)
            {
                if (count != 0)
                {
                    aTeacherStatistics.Courses += ", ";
                }

                aTeacherStatistics.Courses += courseInfo.Code;
                aTeacherStatistics.Courses += "(";
                aTeacherStatistics.Courses += courseInfo.Section;
                aTeacherStatistics.Courses += ")";
                count++;
            }
            teacherStatisticses.Add(aTeacherStatistics);
        }
        var document = new Document(PageSize.A4, 50, 50, 25, 25);
        var output = new MemoryStream();
        var writer = PdfWriter.GetInstance(document, output);
        document.Open();
        var data = teacherStatisticses.ToList();
        document.Add(data);
        Response.ContentType = "application/pdf";
        Response.AddHeader("content-disposition", "attachment;  filename=PartTimeFaculty.pdf");
        Response.BinaryWrite(output.ToArray());
        document.Close();
        return View(teacherStatisticses);
    }

I want to pass a list named 'teacherStatisticses' through document object for making a PDF. My code doesn't work. It showed me following Error  -
Argument 1: cannot convert from 'System.Collections.Generic.List' to 'iTextSharp.text.IElement'

A: I assume that you are using some version of itextpdf for the PDF generation.
The error is in the line:
 document.Add(data);

There is no way to add plain .NET objects into the PDF document. I can not predict the structure of PDF which you`d like to achieve, but the code mentioned above could be written as:
    foreach(var teacher in teacherStatistics)
    {
       var paragraph = new Paragraph(teacher.ToString()); // instead of teacher.ToString() should be some code which translates teacherStatistics projection to the string representation
       document.Add(paragraph);
    }
    //not tested

A lot of useful samples could be found at
     http://developers.itextpdf.com/examples
Basic tutorial for the itextpdf:
http://developers.itextpdf.com/content/itext-7-jump-start-tutorial/chapter-1-introducing-basic-building-blocks


text:
Q: Scala Spark : Difference in the results returned by df.stat.sampleBy() I saw many questions posted on stratifiedSampling, but none of them answered my question, so asking it as "new post" , hoping to get some update.
I have noticed that there is a difference in results returned by spark API:sampleBy(), this is not much significant for small sized dataframe but is more noticeable for large sized data frame (>1000 rows)
sample code:
val inputRDD:RDD[(Any,Row)] =df.rdd.keyBy(x=> x.get(0))
val keyCount = inputRDD.countByKey()
val sampleFractions = keyCount.map(x => (x._1,{(

  x._2.toDouble*sampleSize)/(totalCount*100)})).toMap
val sampleDF = df.stat.sampleBy(cols(0),fractions = sampleFractions,seed = 11L)

total dataframe count:200
Keys count:
A:16
B:91
C:54
D:39
fractions : Map(A -> 0.08, B -> 0.455, C -> 0.27, D -> 0.195)
I get only 69 rows as output from df.stat.sampleBy() though I have specified that sample size expected is 100, of course this is specified as fraction to spark API.
Thanks

A: sampleBy doesn't guarantee you'll get the exact fractions of rows. It takes a sample with probability for each record being included equal to fractions. Depending on a run this value will vary and there is nothing unusual about it.

A: The result is combined from A -> 16 * 0.08, B -> 91 * 0.455, C -> 54 * 0.27, D -> 39 * 0.195 = ( 1.28 rows + 41.405 rows + 14.58 rows + 7.605 rows) which will make around 67 rows


text:
Q: Little-o proof by definition I'm trying to figure out how to prove the following but to no avail.
Given the following functions :
$f(n) = n^3 -4n$
$g(n) = 5n^2 + 3n$
I have to show that $g(n) = o(f(n))$
by definition, that is not using limits or O definitions.
Notice that we say that $f(n)$ is $o(g(n))$ if for any real constant $\epsilon > 0$, there exists an integer constant $n_0 >= 1$ such that $f(n) < \epsilon g(n)$ for every integer $n>=n_0$.
I was trying to use some calculus techniques to solve it.
Here is what I have so far:
I'm looking for $n_0 >= 1$ such that $\epsilon_0 >= (5n^2+3n)/(n^3-4n)$ for every $n>= n_0$
Can someone explain me how can I continue from here? If I solve this inequality I believe It will give me the required $n_0$ for the $\epsilon$.

A: For every $\varepsilon\gt0$, choose $n_\varepsilon\geqslant4$ such that $n_\varepsilon\geqslant8/\varepsilon$. Then, for every $n\geqslant n_\varepsilon$,
$$
g(n)=5n^2+3n\leqslant8(n^2-4)=8f(n)/n\leqslant(8/n_\varepsilon)f(n)\leqslant\varepsilon f(n).
$$
The only nontrivial step is the assertion that $5n^2+3n\leqslant8(n^2-4)$, but this is equivalent to the inequality $3n(n-1)\geqslant32$, which indeed holds for every $n\geqslant4$.

A: Hint as $n$ tends to infinity
$$ \frac{5n^2+3n}{n^3-4n} \sim\frac{5n^2}{n^3}=\frac{5}{n} $$


text:
Q: Tool (javascript) to convert a XML string to JSON What is the best javascript function/plugin/library to convert a XML string to JSON.
I found that tool : http://www.thomasfrank.se/xml_to_json.html, but it does not like strings starting with 0. i.e.: 005321 get converted to 2769 (not cool :( )
My question, what is the best javascript function/plugin/library to convert a XML to JSON?
EDIT : Someone tried one that works fine?

A: Another small library for XML <=> JSON is https://github.com/abdmob/x2js

A: If you're willing to use jQuery, there is:
http://www.fyneworks.com/jquery/xml-to-json/
$.get("http://jfcoder.com/test.xml.php", function(xml){
    var json = $.xml2json(xml);
    $('pre').html(JSON.stringify(json)); // To show result in the browser
});

Using:
<nums>
 <num>00597</num>
 <num>0059</num>
 <num>5978</num>
 <num>5.978</num>
</nums>

Outputs:
{"num":["00597","0059","5978","5.978"]}

http://jfcoder.com/test.php

A: This function has worked pretty well for me:
xmlToJson = function(xml) {
    var obj = {};
    if (xml.nodeType == 1) {
        if (xml.attributes.length > 0) {
            obj["@attributes"] = {};
            for (var j = 0; j < xml.attributes.length; j++) {
                var attribute = xml.attributes.item(j);
                obj["@attributes"][attribute.nodeName] = attribute.nodeValue;
            }
        }
    } else if (xml.nodeType == 3) {
        obj = xml.nodeValue;
    }
    if (xml.hasChildNodes()) {
        for (var i = 0; i < xml.childNodes.length; i++) {
            var item = xml.childNodes.item(i);
            var nodeName = item.nodeName;
            if (typeof (obj[nodeName]) == "undefined") {
                obj[nodeName] = xmlToJson(item);
            } else {
                if (typeof (obj[nodeName].push) == "undefined") {
                    var old = obj[nodeName];
                    obj[nodeName] = [];
                    obj[nodeName].push(old);
                }
                obj[nodeName].push(xmlToJson(item));
            }
        }
    }
    return obj;
}

Implementation:
var jsonText = JSON.stringify(xmlToJson(xmlDoc)); // xmlDoc = xml dom document


text:
Q: Copying images from Gimp to Lotus Notes via clipboard ruined color depth I have for example this image:

When I open it in web-browser and use ctrl-c ctrl-v to lotus-notes, it is copied correctly.

But, when I copy image firstly into gimp, and after that to Lotus Notes, It ruined color depth and images look fuzy. (browser ctrl-c -> ctrl-v GIMP -> ctrl-c in GIMP -> ctrl-v Lotus Notes)

Can anybody please help why this is happening, and how to fix? I need to use ctrl-c+v because of processing big amount of images. Any other method of importing images to Lotus Notes will slow my work.
Thx.
LN 8.5.3 and 7
Gimp 2.8.2 and 2.6
Win 7 and XP
Also Windows Paint do the same,...
EDIT:
Test on rich text in another app. First image is imported from browser, second from gimp:

A: Tested and reproduced (R853FP5/R901). I checked for existing issues and unfortunately it is a known issue with the Windows client.
It has been reported to development as SPR MLEY8TPD2Y. So if you can open a PMR (support call), you can add your customer report to the SPR.
There is no work around, although the Mac Version of Notes correctly pastes the image.


text:
Q: How can I track down what is giving my desktop spam notifications? I'm getting desktop notifications when I log in. They look simply like news headlines. I thought they were some new part of Ubuntu. Clicking on these leads me to websites like investing-review.com with spammy bitcoin-related content pretending to be the BBC.
I don't think I've installed anything which would do this, so I'm puzzled.
I tried running
ps -ef

To see what was running, but the list is huge and nothing obvious jumps out. I'd prefer not to have to reinstall everything, but get to the bottom of this by finding the root cause and removing that.
EDIT: Although I've now worked out what was causing this, it was only by guesswork. It would still be very useful to know how to debug this kind of problem in future.

A: Find the browser that is sending the spam notifications and disable them. For firefox, open firefox and got to the address about:preferences#general (or go to preferences from the rightmost small button on the top with the three lines). Then on the search box that says 'find in preferences' type notifications then set everything to block. Re-enable stuff you like, such as your email.

A: It's possible to go into settings -> notifications on Ubuntu, and disable all notifications, or based on application. If you try disabling "Google Chrome" then restarting to force the condition for popups to appear, you could check if it's actually from the browser you get the notifications.
If notifications still persist, it's something else, try toggling the other options.
If it is Chrome, paste this into chrome URL bar:
chrome://settings/content/notifications
Click here for Google Chrome notification support page
And tweak which sites are allowed to send you push notifications through Chrome.
A re-install of chrome could potentially gain you nothing if you're logged in to the browser with a user, as the settings usually sync to the account.

A: The problem as it turned out was Firefox. I use Mozilla Sync, so my bookmarks, etc were already backed up. To remove Firefox I did:
sudo apt-get remove firefox*

To be safe I moved my .mozilla folder to a backup.
Then after a reboot, I did:
sudo apt install firefox

Then I logged back into Sync and changed my password. Once I could see I had what I needed, I deleted the backup of .mozilla. Thanks to those who posted suggestions, they were helpful and I've upvoted them.


text:
Q: How to handle multiple listeners inside GridView in Android In my app, a GridView has list of contents. Each item is inflated with a layout. Single item inside the gridview contains, an  image and 2 textviews.
I have a requirement that when I click on the image, the image should be replaced with another image and when I click on any other places it should open a popup. I am able to listen to the second event, using OnItemClickListener. It opens the popup. How can I handle the first case? I mean how can I listen to OnClick event of image?

A: In your view adapter, when you set the image resource, also set an onClickListener for the  ImageView.
In my case, holder is a temporary static class which holds 2 TextViews and an ImageView.:
holder.mThumbnailImageView = (ImageView) convertView.findViewById(R.list.thumb);
holder.mThumbnailImageView.setImageResource(thisOrder.getIconValue());
holder.mThumbnailImageView.setOnClickListener(new View.OnClickListener() {
    @Override
    public void onClick(View view) {
        Toast.makeText(parent.getContext(), "image clicked: " + view.getId(), Toast.LENGTH_SHORT).show();
    }
});


text:
Q: What's that supposed to mean vs what does that suppose to mean vs what's that suppose to mean I, for some reason, can't figure out the grammar of the following phrase - "What's that supposed to mean?"...
Why isn't it "What does that suppose to mean?" or "What's that suppose to mean?" I know it's a set phrase, but I still can't fathom how is it grammatically correct, am I missing something? Please help!

A: The expression is "What is that supposed to mean?", and it means what it says: What does "that" mean, according to your supposition/implication?
Understand that "what's" is a contraction for either "what does" or "what is" -- eg, "What's up, doc?"

A: If I write "Life is a bowl of cherries", the meaning is not immediately clear to you. You may imagine that I have a hidden meaning.
But you are not sure of my meaning (I may just mean "Life is simple", or "Life is fruitful"). You are not sure of what I suppose it to mean to you(i.e. what metaphor I suppose I am creating for you to understand). And therefore, you ask me "What is that (my statement) supposed (by me) to mean (to you)?.
The reply would be that I suppose it to mean to you that "Life is very pleasant and easy to enjoy".

A: The semantic of what you consider to be the proper way to express this idea is actually awful, I have to say. The verb "to suppose" is used with subjects that can only be human beings: it's a verb that means "to think", roughly; therefore, in this sentence, where the subject is "that", and we know that this pronoun represents a thing, an idea, a fact, etc. but not a human being, the result is that we imply that inanimates do think, which is nonsense.
This phrase is in fact an idiom (OALD).

*

*be supposed to do/be something
  to be expected or required to do/be something according to a rule, a custom, an arrangement, etc.
What am I supposed to do?
You're supposed to buy a ticket, but not many people do.
I thought we were supposed to be paid today.
The engine doesn't sound like it's supposed to.
You were supposed to be here an hour ago!
Oops—that wasn't supposed to happen.
How was I supposed to know you were waiting for me?
'Yes and no.' 'What is that supposed to mean?' (= showing that you are annoyed)

A: Yes, you're missing something.   You're missing the fact that the agent is supposed to be missing.   That is, we have reason to suppose that the agent will be unmentioned.

* What does that suppose to mean?
   What is that supposed to mean?

Here, we see a difference between active and passive voices.
In the first, whatever that is, it supposes something.   That something which it supposes is missing.   How the "to mean" is meant to attach to the rest of this clause is uncertain.   This isn't a coherent sentence.
In the second, we don't know who supposes, and we just don't care.   To put it in the active voice, someone (maybe everyone) supposes that to mean ... and we've reach the heart of the question:

What does everyone suppose that to mean?

or maybe even

What could anyone suppose that to mean?

Anyone, everyone, someone, just you or just me -- the agent isn't relevant to the question.   We have reason to suppose that the question will be cast in the passive voice.
That is to say, it is supposed to be a passive-voice construction.


text:
Q: Why can't I replay the Fnord level in Peggle Blast? I'm trying to unlock one of the achievements in Peggle 2 related to finding all of the secret pegs.  However, I can't access the last level with Fnord.  Every time I click on it, it says: "Not a good idea... It'd be best not to give Fnord another chance to betray us".
Are there some prerequisites to being able to play this level again, or are you only able to play this level once?  There doesn't seem to be any DLC related to it either.


text:
Q: A word for "wanting everyone else to suffer the same as you"? Let's say I have the following situation:

Student: Professor, do you have the answers for the questions on your textbook?
Professor: No. When I was a student like you, we had to struggle to answer them on our own.

If the professor decided to do so solely because he wanted everyone else to "suffer" the same as he did, did he/she do it out of _____?
As far as I have searched here, I did not find a specific word for this kind of "forcing an empathy".

A: Your question doesn't really seem to be in line with your example. "Spite" could be an answer to your question as posed, although it doesn't hold that precise meaning of the individual having suffered previously.
It seems like your professor just believes that working for the answers will help you learn them better, not that he wants everyone to suffer as he did. Were it the latter, I'd call it "spite," which seems to be your question- but I don't have a word for what I perceive his actual intent as.

A:
The professor refused to provide answers to the exercises, in an
  ill-conceived attempt to toughen us up or impose his own student
  sufferings on us.

Also, I'm getting a bit of a feeling of a hazing ritual, but I haven't been able to come up with a sentence using that.

A: Tough love is the word I would use.
You would be surprised how many students will just look at the answers and think they're able to do the exercises.

A: Although your question is good, your example, even with the edit, is almost as out of place as this hyphenated, two-word answer:

… did he/she do it out of pay-it-forward
  revenge/vengeance?

("Revenge, Paid Forward" from QuinnCreative)


text:
Q: Size of a Git repository vs Time I would like to produce a graph or table of the total repository size vs time (or commit).
Is there a git command or tool that does this? I have tried git log but it does not seem to have an option to export the size of the commits.

A: The size of a commit is very hard to define. First of all, most commits recycle a lot of existing Git objects. If you don't change a file between revision A and B, should the size of B include the size of that file? Also, the repository size itself is not that easily determined either. Due to Git's compression system, it will repack objects from time to time. The way it does that can be influenced by multiple things, so it might not pack the same way if you do it again, resulting in a different total size.
What you could do is check the size of the checked-out tree of every revision. But of course the result you will get there will be far away from the repository's size itself.

A: Git doesn't provide such feature yet.
The best solution would be to iretate over the log and grep the filesize and add'em together.
There is an solition written in PERL by one of the makers of BitBucket (Daniel Rohan):
https://confluence.atlassian.com/plugins/servlet/mobile#content/view/292651328

A: Instead of trying to measure "size" (which does not make sense with a Git repo, as explained by poke), you could visualize "code frequency" (ie the "size" of contributions in term of lines added or removed over time):
The idea comes from "Introducing the New GitHub Graphs"

See "Stupid Git Trick - getting contributor stats", except you wouldn't necessarily use the --author with git log --mumstat, but you can combine git log with --since and --until option.
Something like:
git log --since "OCT 4 2011" --until "OCT 11 2011" --pretty=tformat: --numstat | \
  gawk '{ add += $1 ; subs += $2 ; loc += $1 - $2 } END \
  { printf "added lines: %s removed lines: %s total lines: %s\n",add,subs,loc }' -

A: Apart from coming up with a sensible answer to "what does repository size even mean?", you also have to consider what time should mean to you. The author date of commits? The commit date? When the commit actually became reachable by a particular branch? As opposed to other version control systems, time is often less useful in a Git context.

*

*The date normally shown for a commit in e.g. git log output is normally the point in time when the commit was created for the first time. Commits can bake for days, weeks or even months before even leaving the developer's machine.

*The commit date indicates when a particular commit object was created, so commits that e.g. are rebased or applied to an upstream branch with git format-patch will get a new commit date even though the author date stays the same. Still, with work taking place in separate branches the commit date can be months old.

*Finally, the time a particular commit becomes reachable (which is the closest equivalent to the commit/check-in/submission timestamp recorded by some other version control systems is not recorded by Git. You'd probably have to monitor the git contents by e.g. running a hook to record this information yourself.

A: I put together a python script to create a CSV that will bring you there quite easily: https://gist.github.com/StefanoChiodino/3f749424403c6070dae72dc308724dba
Having looked at the output, I believe it's overestimate the size of each commit for some reason. Anyways, it's quite useful for analysis.
#!/usr/bin/env python3
import csv
import subprocess
import sys

git_rev_list = subprocess.check_output(
    "git log --no-merges --pretty='%H|%an|%aI|%s' origin/master".split(" ")).decode(
    sys.stdout.encoding).rstrip().splitlines()

with open('commit_stats.csv', 'w', ) as file_handler:
    csv = csv.writer(file_handler)
    csv.writerow(["id", "author", "size", "file count", "date", "comment"])

    for git_rev in git_rev_list:
        try:
            commit_size = 0
            commit_id, author, date, comment = git_rev.strip("'").split("|", 3)
            diff_tree = subprocess.check_output(
                "git diff-tree -r -c -M -C --no-commit-id {}".format(commit_id).split(" ")).decode(sys.stdout.encoding)
            for diff in diff_tree.splitlines():
                try:
                    blob_id = diff.split(" ")[3]
                    if blob_id != "0000000000000000000000000000000000000000":
                        cat_file = subprocess.check_output("git cat-file -s {}".format(blob_id).split(" "))
                        commit_size += int(cat_file)
                except:
                    pass
            csv.writerow([commit_id, author, commit_size, len(diff_tree), date, comment])
        except ValueError:
            pass


text:
Q: Setting environment variables in Gatsby I used this tutorial: https://github.com/gatsbyjs/gatsby/blob/master/docs/docs/environment-variables.md
Steps I followed:
1) install dotenv@4.0.0
2) Create two files in root folder: ".env.development" and ".env.production"
3) "follow their setup instructions" (example on dotenv npm docs)
In gatsby-config.js:
const fs = require('fs');
const dotenv = require('dotenv');
const envConfig =
dotenv.parse(fs.readFileSync(`.env.${process.env.NODE_ENV}`));
for (var k in envConfig) {
  process.env[k] = envConfig[k];
}

Unfortunately, when i run gatsby develop, NODE_ENV isn't set yet:
error Could not load gatsby-config

  Error: ENOENT: no such file or directory, open 'E:\Front-End Projects\Gatsby\sebhewelt.com\.env.undefined'

It works when I set it manually:
dotenv.parse(fs.readFileSync(`.env.development`));

I need environment variables in gatsby-config because I put sensitive data in this file:
  {
      resolve: `gatsby-source-contentful`,
      options: {
        spaceId: envConfig.CONTENTFUL_SPACE_ID,
        accessToken: envConfig.CONTENTFUL_ACCESS_TOKEN
      }
    }

How to make it work?
PS: Additional question - As this made me think, I know I shouldn't put passwords and tokens on github, but as netlify builds from github, is there other safe way?

A: You should only use env files when you're comfortable checking those into git. For passwords/tokens/etc. add them to Netlify or whatever build tool you use through their dashboard.
These you can access in gatsby-config.js & gatsby-node.js via process.env.ENV_VARIABLE.
You can't access environment variables added this way in the browser however. For this you'll need to use .env.development & .env.production.

A: I had a similar issue, I created 2 files in the root ".env.development" and ".env.production" but was still not able to access the env file variables - it was returning undefined in my gatsby-config.js file.
Got it working by npm installing dotenv and doing this:
1) When running gatsby develop process.env.NODE_ENV was returning undefined, but when running gatsby build it was returning 'production' so I define it here:
let env = process.env.NODE_ENV || 'development';

2) Then I used dotenv but specify the filepath based on the process.env.NODE_ENV
require('dotenv').config({path: `./.env.${env}`});

3) Then you can access your variables for your config:
module.exports = {
siteMetadata: {
    title: `Gatsby Default Starter`,
},
plugins: [
    `gatsby-plugin-react-helmet`,
    {
      resolve: `gatsby-source-contentful`,
      options: {
        spaceId: `${process.env.CONTENTFUL_ID}`,
        accessToken: `${process.env.CONTENTFUL_TOKEN}`,
        },
    },
],
}

A: I really dislike the .env.production file pattern, our build system sets up and uses env variables and having extra build steps to write those into a file is weird. But Gatsby only whitelists GATSBY_ of the env vars, with no obvious way of adding your own.
But doing that isn't so hard, you can do it by adding something like this in the gatsby-node.js file:
exports.onCreateWebpackConfig = ({ actions, getConfig }) => {
    const config = getConfig();

    // Allow process.env.MY_WHITELIST_PREFIX_* environment variables
    const definePlugin = config.plugins.find(p => p.definitions);
    for (const [k, v] of Object.entries(process.env)) {
        if (k.startsWith("MY_WHITELIST_PREFIX_")) {
            definePlugin.definitions[`process.env.${k}`] = JSON.stringify(v);
        }
    }

    actions.replaceWebpackConfig(config);
};

A: After doing a few searches, I found that we can set environment variables through netlify website, here are the steps:

*

*Under your own netlify console platform, please go to settings

*Choose build & deploy tab (can be found on sidebar)

*Choose environment sub-tab option

*Click edit variables and add/put your credentials in

*Done!


text:
Q: On dual-boot macOS/Ubuntu Mojave install failed with "This disk cannot be used to startup your computer." My box is mid 2012 MacBook Pro, 1 TB HD, Sierra 10.12.6. It has dual-booted with Ubuntu using rEFInd until the High Sierra installation failed, after which I only used Ubuntu. After uninstalling rEFInd I'm attempting to upgrade the macOS side to Mojave and get the error above. I've already run First Aid on the Macintosh HD. Here's the partitioning:
# diskutil list disk0
/dev/disk0 (internal, physical):
   #:                       TYPE NAME                    SIZE       IDENTIFIER
   0:      GUID_partition_scheme                        *1.0 TB     disk0
   1:                        EFI EFI                     209.7 MB   disk0s1
   2:          Apple_CoreStorage Macintosh HD            500.4 GB   disk0s2
   3:                  Apple_HFS Recovery HD             650.0 MB   disk0s3
   4:           Linux Filesystem                         498.8 GB   disk0s4
# gpt -r show disk0
gpt show: disk0: Suspicious MBR at sector 0
       start        size  index  contents
           0           1         MBR
           1           1         Pri GPT header
           2          32         Pri GPT table
          34           6
          40      409600      1  GPT part - C12A7328-F81F-11D2-BA4B-00A0C93EC93B
      409640   977270656      2  GPT part - 53746F72-6167-11AA-AA11-00306543ECAC
   977680296     1269536      3  GPT part - 48465300-0000-11AA-AA11-00306543ECAC
   978949832   974313152      4  GPT part - 0FC63DAF-8483-4772-8E79-3D69D8477DE4
  1953262984      262151
  1953525135          32         Sec GPT table
  1953525167           1         Sec GPT header

Is there a way to install Mojave without reformatting?

A: I deleted the Ubuntu partition and then used macOS utilities, Disk Utility and diskutil to recover that space. Then the upgrade to Mojave proceeded normally. At that point I used these utilities to resize the Macintosh HD partition to half the disk and created a following spacer partition of 128 MiB (see rEFInd forum). I then reinstalled rEFInd from macOS and Ubuntu in the remaining free space. The result is a working Mojave/Ubuntu dual-boot system.


text:
Q: ArrayList Order by KEY Value for ListView Cells I have a ListView that displays Time and Date and a bit of other information that's irrelevant to the issue. They are stored in an ArrayList Hashmap. When loaded into the ListView they are Organized by there ID's by default, Instead they need to be organized by the date and time. This is my code so far.
public void loadListView() {
   productsList = new ArrayList<HashMap<String, Object>>();
    lv = (ListView) getActivity().findViewById(R.id.listview);
    lv.setTextFilterEnabled(true);
    DatabaseHandler db = new DatabaseHandler(getActivity());
    List<SalesCall> salescall = db.getAllSalescalls();
    lv = (ListView) getActivity().findViewById(R.id.listview);
    for (SalesCall cn : salescall) {
        HashMap<String, Object> map = new HashMap<String, Object>();
        map.put(KEY_ID, cn.getID());
        map.put(KEY_NAME, cn.getDoctor());
        map.put(KEY_TIME, cn.getScheduled_time());
        map.put(KEY_DATE, cn.getScheduled_Date());
        map.put(KEY_ALL, cn.getAccount() + ":" + cn.getDoctor());
       productsList.add(map);

    }

    adapter = new ExtendedSimpleAdapter(
            getActivity(), productsList,
            R.layout.listview_item_layout_salescall,
            new String[]{KEY_ID, KEY_NAME, KEY_TIME, KEY_DATE, KEY_ALL},
            new int[]{R.id.id, R.id.fname, R.id.Time, R.id.Date, R.id.All});
    // updating listview

    lv.setAdapter(adapter);
    db.close();
}

How would I sort the data Accordingly?
Edit:
Comparable code
  @Override
      public int compare(SalesCall lhs, SalesCall rhs) {
        if (lhs.getScheduled_Date() == null || rhs.getScheduled_Date() == null)
            return 0;
        return lhs.getScheduled_Date().compareTo(rhs.getScheduled_Date());
    }

A: The implementation of HashMap does not provide any order of the items. The ArrayList keep the order of added data. You should change your flow to have result as you expect.
This is the flow you need to have:

*

*Acquire data in valid order

*Create Mapping

*Display

In your code you use method
List<SalesCall> salescall = db.getAllSalescalls();
If you have provided this data in demanded order then you will not have to sort them before mapping
List<SalesCall> salesCallByDate = db.getSalesCallsAndSortBy(R.id.Date, R.id.Time);
Then when you traverse this List and create mapping into map that is stored in new list the order will be maintain.

A: HashMap won't sort the data by key. Probably you're seeking for TreeMap.
But after reviewing more your code, you're doing this wrong. It would be better to use List<SalesCall> instead of List<Map<String, String>> to pass the data. Probably you will need that SalesCall class implements Comparable accordingly for your sort and if it will pass from different intents, it may also need to implement Serializable.
Basic sample for implementing Comparable:
public SalesCall implements Comparable<SalesCall> {
    @Override
    public int compareTo(SalesCall another) {
        /* algoritm to sort by Date and Time fields */
    }
}


text:
Q: No object create in model after submit form in Django I have a form for add obj to models, no error for the whole process, but also no any objects adding to models. Did I miss somethings?
below is my model, the field is matched to the forms but not all of it.
product_name = models.CharField(max_length=200)
price = models.DecimalField(decimal_places=2, max_digits=10, blank=True)
created = models.DateTimeField(auto_now=True)
img = models.ImageField(upload_to='product', default='xxxxx')
img2 =models.ImageField(upload_to='product', null=True, default='xxxxxx')
img3 =models.ImageField(upload_to='product', null=True, default='xxxxx')
img4 =models.ImageField(upload_to='product', null=True, default='xxxxxxx')
storage_amount = models.PositiveIntegerField(validators=[MinValueValidator(0)])
out_of_storage_or_not = models.BooleanField(default=False)
description = models.TextField(blank=True, null=True)
Hot = models.BooleanField(default=False)
type = models.CharField(
    max_length=2,
    choices=PRODUCT_CHOICES,
    default=xxxxx,
)
status = models.IntegerField(choices=STATUS, default=0)
slug = models.SlugField(max_length=255, unique=True)

forms.py:
class Add_Product(forms.ModelForm):
product_name = forms.CharField()
price = forms.DecimalField()
img = forms.ImageField()
img2 = forms.ImageField()
img3 = forms.ImageField()
storage_amount = forms.IntegerField()
description = forms.CharField(widget=forms.Textarea(attrs={'cols': 80, 'rows': 20}))
Hot = forms.BooleanField(widget=forms.CheckboxInput())
type = forms.ChoiceField(widget=forms.RadioSelect, choices=PRODUCT_CHOICES)
status = forms.ChoiceField(choices=STATUS)
slug = forms.CharField()

class Meta:
    model = Product
    fields = ('product_name', 'price', 'img', 'img2', 'img3', 'storage_amount', 'description', 'Hot', 'type', 'status', 'slug')

views.py:
 if request.method == 'POST':
        form = Add_Product(data=request.POST)
        if form.is_valid():
            product = form.save(commit=False)
            product.save()
        messages.success(request, 'Success')
        return redirect('/')

    else:
        form = Add_Product()
        context = {'form': form}
        return render(request, 'add_product.html', context)

add_product.html:
<form method="POST" class="card-body" >
          {% csrf_token %}

Add Product

            {{ form | crispy }}
    <button type="submit">Submit</button>
</form>

A: you have image files as well soo you need to add enctype to load those image file
<form method="POST" class="card-body" enctype="multipart/form-data">

and its
form = Add_Product(request.POST or None, request.FILES or None)


text:
Q: How to give a program administrator privilige in linux? I am very new in such things so point me if I'm wrong.
I want to execute some terminal commands(to turn of GPU) on my computer on every time my computer starts. Those commands require super user privileges so when I execute them manually I write sudo su then password. But I want to execute those commands with python code. How should I do this.
I tried this code but it failed
import os
os.system('sudo su')
print my_computer_password
#then four lines of command which turn off GPU

these lines of code doesn't work because print statement doesn't fill password dialogue...

A: You could use the subprocess module so you can communicate with it.
import subprocess as sp
prog = sp.Popen(['sudo','whateverprogram'],stdin=sp.PIPE)
prog.stdin.write('password')
prog.communicate()


text:
Q: Swift Minute intervals between two dates I would like to return an array of dates where each date is a 15 minute interval between a startDate and an endDate
i.e : startDate time is 2pm and endDate time is 3pm, desired result would be an array containing the following dates [2:15pm, 2:30pm, 2:45pm] in Date format.
I mustered up some skeleton code but have not yet been able to achieve my desired result.
private func getTimeIntervals(startTime: Date, endTime: Date) -> [Date] {
        let timeIntervals = []
        //get both times sinces refrenced date and divide by 60 to get minutes
        let startTimeMinutes = startTime.timeIntervalSinceReferenceDate/60
        let endTimeMinutes = endTime.timeIntervalSinceReferenceDate/60

        while(startTimeMinutes < endTimeMinutes) {
            // Add each 15 minute Date time interval into the timeIntervalsArray
        }

        return timeIntervals
    }

Any help would be greatly appreciated, thanks in advance.

A: Use the Calendar function date(byAdding:value:to:wrappingComponents:)
func dates(fromStart start: Date,
           toEnd end: Date,
           component: Calendar.Component,
           value: Int) -> [Date] {
    var result = [Date]()
    var working = start
    repeat {
        result.append(working)
        guard let new = Calendar.current.date(byAdding: component, value: value, to: working) else { return result }
        working = new
    } while working <= end
    return result
}

Here is that code in a functioning playground:
import UIKit

func dates(fromStart start: Date,
           toEnd end: Date,
           component: Calendar.Component,
           value: Int) -> [Date] {
    var result = [Date]()
    var working = start
    repeat {
        result.append(working)
        guard let new = Calendar.current.date(byAdding: component, value: value, to: working) else { return result }
        working = new
    } while working <= end
    return result
}

extension Date {
    var localDate: String {return DateFormatter.localizedString(from: self, dateStyle: .medium, timeStyle: .medium)}
}

let threePMComponents = DateComponents(year: 2021, month: 6, day: 7, hour: 15)
guard let threePM = Calendar.current.date(from: threePMComponents) else {
    fatalError()
}

let sixPMComponents = DateComponents(year: 2021, month: 6, day: 7, hour: 18)
guard let sixPM = Calendar.current.date(from: sixPMComponents) else {
    fatalError()
}

print("Start time = \(threePM.localDate)")
print("End time = \(sixPM.localDate)")

let datesInRange = dates(fromStart: threePM, toEnd: sixPM, component: .minute, value: 15)
for item in datesInRange {
    print(item.localDate)
}

The output is:
Start time = Jun 7, 2021 at 3:00:00 PM
End time = Jun 7, 2021 at 6:00:00 PM
Jun 7, 2021 at 3:00:00 PM
Jun 7, 2021 at 3:15:00 PM
Jun 7, 2021 at 3:30:00 PM
Jun 7, 2021 at 3:45:00 PM
Jun 7, 2021 at 4:00:00 PM
Jun 7, 2021 at 4:15:00 PM
Jun 7, 2021 at 4:30:00 PM
Jun 7, 2021 at 4:45:00 PM
Jun 7, 2021 at 5:00:00 PM
Jun 7, 2021 at 5:15:00 PM
Jun 7, 2021 at 5:30:00 PM
Jun 7, 2021 at 5:45:00 PM
Jun 7, 2021 at 6:00:00 PM

If you want the function to "snap" to the next even interval of the specified calendar component it would be more involved.


text:
Q: C - predicting runtime ram usage for a simple application Suppose I have the following program - that take a number (eg 10M) from the command line, creates an array of this size, populates it with random integers, hangs around for 15 seconds and then quits. How much RAM should it take up? (Given an input of 10M)
#include <stdio.h>
#include <string.h>
#include <time.h>
#include <stdlib.h>
#include <unistd.h>

int main(int argc, char **argv)
{
  printf("running\n");
  long long size = atoi(argv[1]);
  printf("%lld\n", size);
  int *myArray = malloc(size * sizeof *myArray);
  printf("allocated array\n");
  srand(time(NULL));
  for (long long i=0;i<size;i++) {
    if (i == 0) {
      printf("first iteration\n");
    }
    int r = rand();
    myArray[i] = r;
  }
  printf("Allocated\n");
  sleep(15);
  printf("Done\n");
}

Given the input
./a.out 10000000

This (in the Mac Activity Monitor) takes up 38.4M.
My question is: Is there a way to predict the RAM usage of a simple C application given these parameters? ie an array of 10M integers.

A: You seem to have 32 bit (4 byte) integers on your system.
10 million integers take 10 million * 4 = 40 million bytes.
40 million bytes = 40000000/1024/1024 = 38.15MB, which is close to what you're seeing.

A: You cannot predict it precisely because of multiple factors including the size of the code in memory, as well as alignment, but for this simple application, you can get pretty close, as Joachim's answer pointed out.

A: Assuming a 32-bit machine, each int takes 4 bytes, so an array of 10M ints will use about 40 MB for the array you're allocating. In addition, it uses memory for the code of the program itself, and all the libraries that it links with.
However, this is all virtual memory. The amount of RAM that it uses depends on what it's doing. If it allocates an array but never uses it, the array may never be loaded into RAM at all. Or after it has used it, some parts may be paged out, so the array may never be all in memory at once. The way that virtual memory is reflected in real RAM use can be hard to predict, if there's enough going on on your system that it can't keep every program's memory in RAM at the same time.


text:
Q: Finding parent of checked out version in ClearCase I want to find the parent of a checked out file in ClearCase from a Bash script. For example, if I type ct ls I get this:
$ ct ls some_file
some_file@@/main/some/branch/CHECKEDOUT from some_file@@/main/some/branch/6   Rule: CHECKEDOUT

I want to find the parent version (some_file@@/main/some/branch/6) from a script. Sure I can use awk or similar text processing tools, but I think that's a very ugly solution, and can easily break for more exotic file names (for example if it has spaces or the string "from" in it).

A: Use the "%PSn" format of fmt_ccase (cleartool describe)
 cleartool describe -fmt "%PSn" some_file@@/main/some/branch/CHECKEDOUT

 %PSn

Predecessor Short name:
  For a version, a short form of the predecessor version's version ID: branch-pathname/version-number.
  For other objects, the null string.

Note that for @@/main/0 (which all elements, files or directories, have), it will also return a null string.

The OP petersohn mentions that it is similar to:
cleartool describe -short -pred some_file@@/main/some/branch/CHECKEDOUT


text:
Q: How to fill a 2D array with user inputted values? I'm currently working on a program in java to fill a 2D array with user inputted values. The program works perfectly when both the rows and columns are specifed to the same value (square matrix). But, when the values are different, it doesn't print and throws an index out of bounds exception and I can't seem to figure out why. I have attached my code below.
public static void main(String[] args) {
    Scanner console = new Scanner(System.in);
    int x; //columns
    int y; //rows

    System.out.println("Enter the number of rows of the matrix:");
    y = console.nextInt();
    System.out.println("Enter the number of columns of the matrix:");
    x = console.nextInt();

    int[][] matrix = new int[y][x];
    fillMatrix(y, x, matrix);
}

public static void fillMatrix(int row, int col, int[][] matrix) {
    Scanner console = new Scanner(System.in);
    int quantity = (row * col); //number of numbers in matrix
    System.out.println("Please enter " + quantity +
            " integers separated by spaces:");
    for (int cinput = 0; cinput < row; cinput++) { //column
        for (int rinput = 0; rinput < col; rinput++) { //row
            //Read the line of integers to fill positions in the array.
            matrix[cinput][rinput] = console.nextInt();
        }
    }
    System.out.println();
    for (int i = 0; i < col; i++) {
        for (int j = 0; j < row; j++) {
            //Outputs the array in a xy grid.
            System.out.print(matrix[i][j] + " ");
        }
        System.out.println();
    }
}

A: What I would do is make a copy of all the numbers that you need to put into the matrix.
Hold a counter that will be increased only when you put a value into the matrix.
Continue Increasing the counter until you have no more values to put. When you are done simply get out of the loop.
Something like this
Scanner myScanner = new Scanner (System.in);
int x; //columns
int y; //rows
System.out.println("Enter the number of rows of the matrix:");
y = myScanner.nextInt();
System.out.println("Enter the number of columns of the matrix:");
x = myScanner.nextInt();

int [][] matrix = new int [x][y];

myScanner.nextLine();
System.out.println("Enter the numbers seperated by space:");
String input = myScanner.nextLine();

String tmp            [] = input.split(" "); //holds the numbers that are inputted (String)
int    numbers        [] = new int[tmp.length];//array that holds the parsed numbers

for(int i = 0 ; i <numbers.length; i++)
  numbers[i] = (int)(tmp[i].charAt(0) - '0');  //parsing the numbers

// Logic that matters
int counter = 0;

for(int k = 0; k < matrix.length && counter < numbers.length; k++)
{
 for(int j = 0 ; counter < numbers.length &&  j < matrix[k].length; j++)
 {
     matrix[k][j] = numbers[counter];
     System.out.print(matrix[k][j]+" ");
     counter = counter + 1;
 }
 System.out.println("");
}

Input-
Enter the number of rows of the matrix:
3
Enter the number of columns of the matrix:
1
Enter the numbers seperated by space:
1 2 3

Output -
1 2 3

A: In your output code, change the order of i and j.
So change:
matrix[i][j]

To:
matrix[j][i]

And you probably should swap the order of the for loops as well so the row is on the outside and the column is on the inside.
All together, that'd look like:
System.out.println();
for(int j = 0; j < row; j++)
{
    for(int i = 0; i < col; i++)
    {
        System.out.print(matrix[j][i] + " ");
    }
    System.out.println();
}


text:
Q: service stack web app AD FS authentication sample in VS2010 and .net 4 1) I am looking for AD FS2 authentication sample using service stack .net.
Unauthenticated user should be redirected to SSO page (adfs2, relay proxy) and after successful identification redirected to servicestack.net web app.
I try to start up using https://www.nuget.org/packages/Microsoft.IdentityModel.Tokens.JWT VS2012 is required.
2) What should be implemented CredentialsAuthProvider or IAuthProvider? User authenticates on SSO page.
3) I try use only razor + ss.net without MVC controllers

A: Create a class that inherits from CredentialsAuthProvider and overrides TryAuthenticate method to insert your own authentication logic.
To redirect to SSO page, you can create a Controller class which inherits from ServiceStackController (ServiceStack.Mvc assembly) and override LoginRedirectUrl with something like
    public override string LoginRedirectUrl
    {
        get
        {
            return "~/login?redirect={0}";
        }
    }


text:
Q: Does this class of triangles satisfy a certain geometric inequality? If $\Delta{}ABC$ is a triangle, call the segment perpendicular to $AB$ and containing $C$ the altitude segment at $C$. In brief my question is the following: is it true that for all $0<\theta<\frac{\pi}{2}$ and all triangles $\Delta{}ABC$ satisfying $\measuredangle{}ACB=\theta$, there exists a point $P$ on the altitude segment at $C$ such that $PA+PB+PC<AC+BC$? See the figure below for an example.

Now for some context: I have read in The Secrets of Triangles: A Mathematical Journey by Alfred S. Posamentier and Ingmar Lehmann that if $AB$ is the shortest side of triangle $\Delta{}ABC$ and $P$ is any point in the interior of $\Delta{}ABC$, then $PA+PB+PC<AC+BC$. (The "proof" they give seems rather incomplete.)
While playing with the geometry of the points $A,B,C,P$, I noticed that for many triangles that do not satisfy the condition that $AB$ be the shortest edge of the triangle $\Delta{}ABC$, there nonetheless often exists a point $P$ in the interior of $\Delta{}ABC$ (and especially on the altitude segment at $C$) such that $PA+PB+PC<AC+BC$.
For certain reasons, I am interested in (and am restricting to) the case when $0<\measuredangle{}ACB<\frac{\pi}{2}$ and $P$ is required to lie on the altitude segment at $C$. Is one always guaranteed the existence of such a point $P$ satisfying $PA+PB+PC<AC+BC$ whenever $0<\measuredangle{}ACB<\frac{\pi}{2}$?
Addition: Is it any easier under the further assumption that $\Delta{}ABC$ be acute? This assumption guarantees that the orthocenter lie in the interior of $\Delta{}ABC$. I am quite interested in this sub-case.

A: If $AB\leq AC$ and $AB\leq BC$ so it's true for any point $P$ inside the triangle.
I hope at least this fact would be completed.
Indeed, let $D\in AC$, $E\in BC$, $P\in DE$ such that $DE||AB$ and $CE=kBC$.
Thus, $CD=kAC$ and by the triangle inequality we obtain:
$$PA+PB+PC<AD+DP+BE+EP+PC=AD+BE+DE+PC=$$
$$=(1-k)AC+(1-k)BC+kAB+PC<$$
$$<(1-k)AC+(1-k)BC+kAB+\max\{DC,EC\}=$$
$$=(1-k)AC+(1-k)BC+kAB+k\max\{AC,BC\}=$$
$$=AC+BC+k\left(AB-AC-BC+\max\{AC,BC\}\right)\leq AC+BC.$$


text:
Q: Reading a FILE and using fscanf goes into an infinite loop Here is the function that is given a FILE to scan:
void scan(FILE *file) {

    while (true) {
        char s1[1001];
        int result = fscanf(file, "%10s", s1);
        printf("%d\n", result);
        s1[1001] = '\0';
        if (result == EOF) break;
    }

}

I use fopen on file before passing it to this function.
It prints out -1 in an infinite loop, but it doesn't break. How come?

A: You have an off-by-one error when forcing the null terminator in s1, this:
s1[1001] = '\0';

runs past the end of s1, it should be:
s1[1000] = '\0';

When you declare an array in C as char s1[X];, the X is the number of elements in the array and since C arrays are indexed starting from zero, the last element is s1[X-1].
This off-by-one could be changing the value of result between the printf and the result == EOF check.

A: I guess it depends on what is s1.
Make sure its a char s1[ appropriate_size ] and not char * s1.
Its working great in my case:


text:
Q: Timeout on socket io listeners I saw this documentation for socketio emit() with timeout implementation
https://socket.io/docs/v3/emitting-events/#acknowledgements
I am implementing it on listeners.
I have a code as follows:
app.post('/submitmessage', async (req, res) => {
  const reqBody = req.body;
  const roomId = reqBody['custom-roomid'];

  socketConnection.join(roomId);
  const hasRoom = io.sockets.adapter.rooms.has(roomId);
  if (hasRoom) {
    io.to(roomId).emit("room created", {
     roomId: roomId,
     data: reqBody.sendData
     });
   }
   // this emit has a listener on client displaying a modal with message and buttons
   // like SAVE, OK, CANCEL
   io.to(roomId).emit("question", {
     data: reqBody.sendData,
     browserId: reqBody.browserId,
     sessionId: reqBody.sessionId,
     roomId: roomId
   });
   let reply = '';
   // this listener is listening for which button was clicked by the user on the
   // client passed on by variable warres
   socketConnection.on('return-warning-response', ({ warres }) => {
      reply = warres;
   });
   // waiting for 2 secs
   await sleep(20000);
   socketConnection.leave(roomId);
   if (reply === '') {
     res.sendStatus(404);
   }
   res.send(reply);
  });

When I implement it on the listener like below:
  socketConnection.on('return-warning-response', ({ warres }), withTimeout(() => {
    console.log("success!");
  }, () => {
    console.log("timeout!");
  }, 20000));

It gives error: UnhandledPromiseRejectionWarning: ReferenceError: warres is not defined
Is there an alternative for a timeout functionality on listeners?


text:
Q: strcmp returns unexpected value in C I'm new to C, I have lines of code look like this:
char user[16];
fgets(user,16,stdin);

I typed "zeyang" on the keyboard, and I have another code:
char pwname[1000];
pwname="zeyang";

Then I use strcmp to compare user and pwname:
strcmp(user, pwname);

The return value is a negative number, I expect it to be 0, because they are all "zeyang". Why it isn't 0?

A: fgets includes the typed newline if there's room.  You're comparing "zeyang\n" with "zeyang".  From the fgets(3) man page:

The newline, if any, is retained.

A: The first string coming from stdin contains an additional newline character.

A: The problem is that the sentence you enter will be terminated by a new line character. (I guess you pressed ENTER when you have finished to insert characters. :D
In this case I would use strncmp :
strncmp(user,pwname,strlen(pwname));

This code won't compare the new line character.


text:
Q: How can I retrieve a Featured Image thumbnail using only the Post_title? Is it possible to get the Wordpress featured image of a post using only the post_title name?
I know it can be done with post->ID but I only have the post_title name to work with and this is outside of the loop.

A: You can try the following:
/**
 * Get the featured image by post title (Simple version)
 *
 * @see    http://wordpress.stackexchange.com/a/158344/26350
 * @param  string $title   Post title
 * @param  mixed  $size    Featured image size
 */

function get_featured_image_by_post_title_wpse_simple( $title = '', $size = 'thumbnail' )
{
    $obj  =  get_page_by_title( $title, OBJECT, 'post' );
    return ( is_object ( $obj ) ) ? get_the_post_thumbnail( $obj->ID, $size ) : '';
}

or this extended version:
/**
 * Get the featured image by post title (Extended version)
 *
 * @see    http://wordpress.stackexchange.com/a/158344/26350
 * @param  string $title     Post title
 * @param  mixed  $size      Featured image size
 * @param  string $post_type Post type
 * @param  string $default   Default image url
 * @return string $html      Featured image HTML
 */

function get_featured_image_by_post_title_wpse_ext( $title = '', $size = 'thumbnail', $post_type = 'post', $default = '' )
{
    // Search by post title:
    $obj  = get_page_by_title( $title, OBJECT, $post_type );

    // Featured image:
    if( is_object( $obj ) && has_post_thumbnail( $obj->ID ) )
        $html = get_the_post_thumbnail( $obj->ID, $size );
    else
        $html = sprintf( '<img src="%s" alt="">', esc_url( $default ) );

    return $html;
}

where use get_page_by_title() to locate the post by title.
Usage examples:
 // Simple:
 echo get_featured_image_by_post_title_wpse_simple( 'Hello World!', 'large' );

 // Extended:
 echo get_featured_image_by_post_title_wpse_ext( 'My Car', 'full', 'post', '/car.jpg' );

Hopefully you can extend this to your needs.


text:
Q: Firefox extension development firefox4 So I've been working on updating old extensions for use with FF4 and Gecko 2 but I am having some issues where I am getting an error that says, classID missing or incorrect for component....
Has anyone else had a similar issue or know of how to get around this?
function jsshellClient() {
  this.classDescription = "sdConnector JavaScript Shell Service";
  this.classID = Components.ID("{54f7f162-35d9-524d-9021-965a3ba86366}");
  this.contractID = "@activestate.com/SDService?type=jsshell;1"
  this._xpcom_categories = [{category: "sd-service", entry: "jsshell"}];
  this.name = "jsshell";
  this.prefs = Components.classes["@mozilla.org/preferences-service;1"]
      .getService(Components.interfaces.nsIPrefService)
      .getBranch("sdconnector.jsshell.");
  this.enabled = this.prefs.getBoolPref("enabled");
  this.port = this.prefs.getIntPref("port");
  this.loopbackOnly = this.prefs.getBoolPref("loopbackOnly");
  this.backlog = this.prefs.getIntPref("backlog");
}
jsshellClient.prototype = new session();
jsshellClient.prototype.constructor = jsshellClient;

When calling generateNSGetFactory on the prototype for this it gives an error in the Error Console in FF4 complaining about the classID. I'm pretty sure that nothing else is using the same GUID so I don't see the problem.

A: An important change in JS XPCOM components in Fx4 is that they now need to be registered in the chrome.manifest, see this page of documentation on the changes.

A: The special properties used by XPCOMUtils, like classID, contractID, and so on, have to be defined on Class.prototype, not in the constructor function, as you did: https://developer.mozilla.org/en/XPCOMUtils.jsm#Class_declaration
As for the other question, you posted in a comment, please post it in a different question, if it's still relevant, with the necessary code provided.


text:
Q: Have a parameter applied to service for Upstart I want to run my webcit service with the -f option, how do I put that in the service script (/etc/init.d/webcit)?
The lines that look relevant are:
RUNDIR=/var/run/webcit
PATH=/sbin:/usr/sbin:/bin:/usr/bin
DESC="Citadel Groupware Webserver "
NAME=webcit
DAEMON=/usr/sbin/$NAME
DAEMON_ARGS=""
PIDFILE=$RUNDIR/$NAME.pid
SCRIPTNAME=/etc/init.d/webcit
SENDCOMMAND=/usr/sbin/sendcommand
DEFAULT=/etc/default/webcit
LOGDIR=/var/log/webcit/

A: Open the file /etc/default/webcit and change the first line to
export WEBCIT_APACHEFLAG='-f'

then restart the service
sudo service webcit restart


text:
Q: Elasticsearch process run under weird username I have Elasticsearch 1.7.3 running successfully on CentOS7. However, I observed:
%ps -aux | grep elastic

**209**      10504 85.0 29.2 36122740 19283600 ?   SLl  04:02   0:05
/usr/bin/java -Xms30g -Xmx30g -Djava.awt.headless=true -XX:+UseParNewGC
-XX:+UseConcMarkSweepGC -XX:CMSInitiatingOccupancyFraction=75
-XX:+UseCMSInitiatingOccupancyOnly -XX:+HeapDumpOnOutOfMemoryError
-XX:+DisableExplicitGC -Dfile.encoding=UTF-8 -Delasticsearch -Des.pidfile=/var
/run/elasticsearch/elasticsearch.pid -Des.path.home=/usr/share/elasticsearch

As we can see userid is 209. It supposed to be elasticsearch or root right ?


text:
Q: How to parse the html to store the elements as an array I am having a html text below.

Instant office.

Just click your Surface Pro 3 into the dock to go from tablet to full desktop PC. With an Ethernet port, Mini DisplayPort and five USB ports – three USB 3.0 and two USB 2.0 ports – you can attach your HD monitor, full-size keyboard, printer and more.

All powerful.

Docking Station delivers plenty of power at 48W. You can work on your device, run or charge your favourite accessories, and still have ample power to charge your Surface Pro 3 battery.

Product Features

Mini DisplayPort Video Output
The mini DisplayPort connection delivers high-definition video resolution of up to 3840 x 2600 DPI.

USB Ports
Docking Station includes five USB ports – three USB 3.0 and two USB 2.0 ports. Transfer large files to an external drive, plug in a USB printer or headset, charge multiple accessories, and more.

Gigabit Ethernet Port
The gigabit Ethernet connection is super fast, with data transfer rates of up to 1 billion bits per second¹.

48W Power Supply
The 48W power supply quickly recharges your Surface battery while you work, so you can hit the road or the halls in no time with a fully-charged device.

Summary

Transform your Surface Pro 3 into a complete desktop workstation

Connect to your favourite accessories

Power and charge your Surface Pro 3

I want to parse the above html and display h2 value and then p value in sequence.I want to store it as array where h2 as key and
 as value.
I have tried with xpath->query and also regualr expressions,But unable to display like that.
Can you please suggest me how to procees

A: Try http://simplehtmldom.sourceforge.net/
`
$arr = [];
foreach($html->find('h1') as $header) {
    $nextSibling = $header->nextSibling();
        if (!empty($nextSibling) and $nextSibling->tag === 'p') {
            $arr[$header->plaintext] = $nextSibling->plaintext;
        }
}

`


text:
Q: What could be blocking glGetTexImage in Unreal Engine? This question is a bit abstract, but I am pretty stumped here so I figured I'd ask.
Context
I am using OpenGL to render content from an emulator and then I read the framebuffer from the GPU memory and write it to the CPU. The issue I'm having happens when I read the framebuffer from the GPU memory using glGetTexImage. Here is the code in question if you really want to go deep.
Problem
Something is blocking my call to glGetTexImage (copies a texture from gpu memory to cpu memory) in Unreal Engine. I am using a separate renderer and thread than Unreal Engine is using so I figure it wouldn't conflict. I think it has something to do with how the engine synchronizes with the rendering thread. I have some evidence below.
Evidence and Theory
The y-axis is the time each call takes in milliseconds and the x-axis is realtime. The green graph is my call to glGetTexImage. The Blue line is the time it takes the gamethread to process a frame and the redline is the time it takes the render thread to process a frame. In this example I'm totally GPU bound the game thread is just stalling for the render thread according to the profiler (not shown). Based on the graph it looks like glGetTexImage is stalled until about one or two frames are rendered. I know that in Unreal Engines documentation it says that

In Unreal Engine 4 (UE4), the entire renderer operates in its own
thread that is a frame or two behind the game thread.

Any guidance would be helpful
I don't really expect any one to know what's going wrong here exactly if you have any ideas though or advice I'd be greatful to hear it. I don't know what mechanism is in play that stops the call to glGetTexImage until Unreal Engine has rendered one or two frames. The two renderers are completely mutually exclusive in their operation I'm really not sure how one can effect the operation of another. It could be a side effect based on how my graphics driver works or something. I tried using DirectX11 and Vulkan for the Unreal Engine renderer and they both cause the same problem. If anyone has any ideas what's going on or knows of any good debugging tools that will diagnose what's blocking the call I'd really appreciate it.

A: Any OpenGL function which takes a pointer to client memory must be finished accessing that pointer before returning control to your CPU. So when you call glGetTexImage on an image you have rendered to, the GPU must conclude that rendering process in its entirety, then copy the rendered data into your memory.
Despite the fact that you have different threads sending work to the GPU, the GPU itself may only be able to do one set of work at any particular time. It therefore may interleave execution of work as it sees fit, and the competition of work from one source may have to wait for the completion of work from another source.
So if UE and yourself are throwing some rendering commands at the GPU, the UE work may have gotten there first. Which means that when you wait for your work to finish, you are also waiting for the UE work to finish.
And even if the GPU does allow for multiple queues of work to be completed simultaneously, UE's work is still going to consume some GPU resources from your work. It's going to be using shader execution units and ROPs that your work might have used.
In short, I would be more surprised if the glGetTexImage call wasn't affected by UE's work.
If you need to avoid stalling your CPU thread, then you need to do an asynchronous read from the render target. This means doing a pixel transfer into a buffer object, then waiting until the transfer is done by checking a fence sync object, and only after all of that, reading the data from the buffer.


text:
Q: Why "OnClickListener" is not working I can't understand why this simple code is not working.
This code suppose to set the color of the button's text to blue, that's all.
I only added to a new created project the lines :
 final Button btn = (Button) findViewById(R.id.button1);
    btn.setOnClickListener(new View.OnClickListener() {
    @Override
    public void onClick(View v) {
            // Perform action on click
             btn.setTextColor(Color.BLUE);
        }
    });

The full code :
package com.example.b;

import android.graphics.Color;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v7.app.ActionBarActivity;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;

public class MainActivity extends ActionBarActivity {

protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    final Button btn = (Button) findViewById(R.id.button1);
    btn.setOnClickListener(new View.OnClickListener() {
    @Override
    public void onClick(View v) {
            // Perform action on click
             btn.setTextColor(Color.BLUE);
        }
    });

    if (savedInstanceState == null) {
        getSupportFragmentManager().beginTransaction()
                .add(R.id.container, new PlaceholderFragment())
                .commit();
    }
}

@Override
public boolean onCreateOptionsMenu(Menu menu) {

    // Inflate the menu; this adds items to the action bar if it is present.
    getMenuInflater().inflate(R.menu.main, menu);
    return true;
}

@Override
public boolean onOptionsItemSelected(MenuItem item) {
    // Handle action bar item clicks here. The action bar will
    // automatically handle clicks on the Home/Up button, so long
    // as you specify a parent activity in AndroidManifest.xml.
    int id = item.getItemId();
    if (id == R.id.action_settings) {
        return true;
    }
    return super.onOptionsItemSelected(item);
}

/**
 * A placeholder fragment containing a simple view.
 */
public static class PlaceholderFragment extends Fragment {

    public PlaceholderFragment() {
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
            Bundle savedInstanceState) {
        View rootView = inflater.inflate(R.layout.fragment_main, container, false);
        return rootView;
    }
}

}

A: Most likely the button is in the fragment and not the activity. If so, move your findViewById and your setonclick code into your PlaceHolderFragment.


text:
Q: Gravitational force and Electromagnetic force? I found this interesting note in one of my textbooks,

The enormous strength of the electromagnetic force compared to gravity is evident in our daily life. When we hold a book in our hand, we are balancing the gravitational force on the book due to the huge mass of the earth by the 'normal force' provided by our hand. The latter is nothing but the net electromagnetic force between the charged constituents of our hand and the book, at the surface in contact. If electromagnetic force were not intrinsically so much stronger than gravity, the hand of the strongest man would crumble under the weight of a feather! Indeed, to be consistent, in that circumstance, we ourselves would crumble under our own weight!

What does this mean?

A: The notion of "weak gravity" is "not even wrong"! It's comparing oranges to apples: it's meaningless to compare a dimension-full interaction (gravity) with a dimensionless interaction (standard model interactions such as the electromagnetic force), if no circumstance (e.g the specific charges and masses in comparison) is provided.
The Nobel laureate Frank Wilczek actually wrote a whole book ( The Lightness of Being) about what should be the right question: Given that the "charge" of the gravitational force is mass (energy tensor), the correct question is why are the masses of the elementary particles so small compared with the Planck scale?
This leads you to the nagging issue of natureness/hierarchy problem (the unnatural gap between the Planck mass and the weak scale/Higgs mass).
As of yet, mortal physicists are still scratching their heads and fretting about this nasty "naturalness/hierarchy/fine-tuning problem". The world's best minds are loosing sleeping on it (ask Lisa or Nima) and yet there is no answer.

To give you some thought experiment of "strong" gravity:

*

*If the electron mass is increased to the mass of a flea egg ($10^{-8}$ kg,
the plank mass), the gravitational attraction between electrons will
be in balance with the repulsive electronic force. In technical
jargon, the Schwarzschild radius and the Compton wavelength are of
the same order for this case.

*If the electron mass is increased to the mass of a chicken egg, the
gravitational force between electrons will trump the electronic force
and electrons will be crushed into an electron black hole by gravity. Of course,
true quantum gravity effects will be the dominant one in this case, the conventional semi-quantum black hole reasoning (a la Stephen Hawking) shall be taken with a grain of salt.

A: I think the part about electromagnetic force being exponentially stronger than gravitation got through to you!(An easy way to picture this is how static electricity can lift up things against the pull of the earth!) About the feather,the way you are able to support the feather against the gravitational pull of the earth is because of the electromagnetic forces exerted by your hand on the feather and vice versa. If these were much much weaker something as little as a feather would be able to crumple your hand, that is if it hadn't already been crumpled by gravity before that!
I've read in The Briefer History of Time (Stephen Hawking), that even very slight changes in the strength of the fundamental forces can cause great imbalance. If the electromagnetic force was stronger, atoms wouldn't be as stable as they are, and if it was weaker, atoms might not form at all, so the chances of life existing would be zero!
If there was a sudden change, hypothetically, this instant, the whole world could possibly crumble. But if that actually was the case we wouldn't even have been here.

A: The weak, electromagnetic, and strong fundamental forces can all be quite important, depending on the energy and distance scales of the phenomenon in question. How about gravitation? It is negligible, at least for what concerns the energies we can reach in particle accelerators (in fact, gravity is not even included in the  the Standard Model). Gravity manifests its power only at the macroscopic scale or at the unreachable Planck  scale.
This "puzzle" of "weak gravity" is an unsolved problem in theoretical physics, known as the Hierarchy Problem.
You can easily see that gravity is really "weak" at the fundamental level: in the static limit, the electric and gravitational force laws are both inverse square laws, so if one computes the ratio of the forces between two bodies, the distances cancel.
Take two point particles with masses $m_1$, $m_2$ and charges $q_1$, $q_2$. You have the gravitational  force and the electric Coulomb force (CGS units are used)
$$
F_G = G \frac{m_1 m_2}{d^2}
\qquad \quad
F_C = \frac{q_1 q_2}{d^2}
$$
Clearly (depending on the actual values of $m_1$, $m_2$, $q_1$ ,$q_2$) you may have that $F_G > F_C$, or the other way round.
However, for (charged) elementary particles, you always have that $F_G \ll F_C$. In particular, if you use two electrons  ($m_1=m_2=m_e$,
$q_1=q_2=q_e$), then you have
$$
F_G / F_C =  \frac{G m_e m_e}{q_e q_e} = G \left(\frac{m_e}{q_e} \right)^2 \sim 10^{-42}
$$
where the quantity in the parentheses is the mass to charge ratio first measured by Thompson. As you see $F_G \sim 10^{-42}F_C$, independently on the distance $d$: the gravity attraction is really extremely weak.
In an Hydrogen atom you should compare the attraction between the electron and the proton (i.e. the Hydrogen nucleus). The proton is $\sim 2000$ times more massive than the electron so $F_G$ is $2000$ times bigger than the electron-electron gravitational attraction considered before. In this case you should find $F_G/F_C \sim 10^{-39}$. Still a super small number, telling us that there is no need to include gravity when studying the atomic structure.
Clearly if you don't use fundamental particles but, say, planets (that are almost neutral but have a huge mass), then $F_G$ wins. However, using planets and stars is, clearly, not in the spirit of the Hierarchy problem.

A: This sort of thing just compares the strength of gravity to the strength of EM. It is a bit of a "wow" factor in popular science to say that all the earth's gravity is resisted by a few electrons as you hold something above the ground or whatever. As the top commenter pointed out, this is technically comparing apples to oranges, and the right question is not "why is gravity so weak" but rather "why are things so light" instead. That may be above your needs though.


text:
Q: MSDTC on SQL Server 2012 with mount point for data disk I have installed a new SQL Server 2012 instance on a cluster. The installation went fine but when I've added the MSDTC as resource of the instance, it went wrong. When I just added it, the MSDTC was online but when I tried my first failover, it refused to go online. The error message was "MSDTC failed".
My configuration is:
a physical drive disk (let say J:) with two mount points "DATA" and "LOG".
I read some people who experienced this kind of errors with mount points and SQL Server 2008 but nothing with 2012.
I tried to create the "MSDTC" folder on the physical drive (the J: one) but nothing better.
Does anyone know something about it or know how to configure the MSDTC and force it to use the J: drive?

A: When parametrized, the dependency disk is the disk on which the msdtc will create its directories. This disk must NOT be a mount point.
Hope it can help someone


text:
Q: Dereferencing lists inside list in Python When I define a list in a "generic" way:
>>>a=[[]]*3
>>>a
[[],[],[]]

and then try to append only to the second element of the outer list:
>>>a[1].append([0,1])
>>>a
[[[0,1]], [[0,1]], [[0,1]]]

it appends to all elements of the outer list as can be seen above, probably due to the fact that the elements are references to the same list and not different lists (why does it work that way?). How can I actually create a list in the same "generic" way, such that the inner lists would be different lists and not just references. Thanks.

A: You are correct, they are all references to one list.
[[] for _ in range(3)]

is a common way to create a list of independent empty lists. You can use xrange on Python 2.x, but it won't make a difference if the length is actually as small as in your example.
Not sure how to explain the reason for this (the reason is that it's implemented this way), but you can see that this behavior is documented (at least in passing) here:
Operation       Result                              Notes
s * n, n * s    n shallow copies of s concatenated  (2)

The word "shallow" here means exactly that: the elements are copied by reference. "Note 2" at the linked page also answers your question.


text:
Q: Haskell package for sampling from standard probability distributions I would like to do some Monte Carlo analysis in Haskell. I would like to be able to write code like this:
do n <- poisson lambda
   xs <- replicateM n $ normal mu sigma
   return $ maximum xs

which corresponds to the stochastic model
n ~ Poisson(lambda)
for (i in 1:n)
  x[i] ~ Normal(mu, sigma)
y = max_{i=1}^n x[i]

I can see how to create the necessary random-sampling monad pretty easily. However, I would prefer not to have to implement samplers for all of the standard probability distributions. Is there a Haskell package that already has these implemented?
I have looked at package random-fu, which has been stalled at version 0.2.7 for three years, but I can't make sense of it; it depends on typeclasses MonadRandom and RandomSource, which aren't well explained.
I've also looked at package mwc-probability, but I can't make sense of it either -- it seems you have to already understand the PrimMonad and PrimState typeclasses.
Both of these packages strike me as having overly complex APIs, and seem to have entirely abandoned the standard random-number-generation framework of Haskell as found in System.Random.
Any advice would be appreciated.

A: Well, if you want to be able to write code like this:
do n <- poisson lambda
   xs <- replicateM n $ normal mu sigma
   return $ maximum xs

then you presumably want to use random-fu:
import Control.Monad
import Data.Random
import Data.Random.Distribution.Poisson
import Data.Random.Distribution.Normal

foo :: RVar Double
foo = do
  n <- poisson lambda
  xs <- replicateM (n+1) $ normal mu sigma
  return $ maximum xs

  where lambda = 10 :: Double
        mu = 0
        sigma = 6

main :: IO ()
main = print =<< replicateM 10 (sample foo)

I'm not sure that lack of updates over the past three years should be a deciding factor.  Have there really been that many exciting advances in the world of gamma distributions?
Actually, it looks like mwc-probability works about the same:
import Control.Monad
import System.Random.MWC.Probability

foo :: Prob IO Double
foo = do
  n <- poisson lambda
  xs <- replicateM (n+1) $ normal mu sigma
  return $ maximum xs

  where lambda = 10 :: Double
        mu = 0
        sigma = 6

main :: IO ()
main = do
  gen <- createSystemRandom
  print =<< replicateM 10 (sample foo gen)

A: I figured out the packages mwc-random and statistics sufficiently to make them usable for my purposes. To make them easier to use, I defined some wrappers, described below. The complete set of packages my solution uses is transformers, vector, mwc-random, and statistics.
First, here are the needed language extensions and imports:
{-# LANGUAGE RankNTypes #-}
{-# LANGUAGE FlexibleContexts #-}

import Control.Monad (replicateM)
import Control.Monad.ST
import Control.Monad.Trans.Reader
import qualified Data.Vector as V
import Data.Vector.Generic hiding (replicateM, sum, product)
import Data.Word
import System.Random.MWC (Gen)
import qualified System.Random.MWC as R
import Statistics.Distribution
import Statistics.Distribution.Normal

I define a random-sampling monad Rand that hides from the user the need to understand PrimMonad and PrimState, and provides some needed utilities. (If you're interested in the details, Gen s a is a uniform PRNG that returns values of type a, ST s is a state-transformer monad, and the uninstantiated type variable s is part of a type-system hack that prevents state-updating side effects from escaping the monad.) An unfortunate feature of the mwc-random and statistics packages is that the primitive PRNG, based on Marsaglia's MWC256 algorithm, is hardwired-in; you cannot substitute a different PRNG.
type Rand0 s a = ReaderT (Gen s) (ST s) a
type Rand a = (forall s. Rand0 s a)  -- the random-sampling monad

-- A draw from the Uniform(0.0, 1.0) distribution
uniform01 :: Rand Double
uniform01 = ask >>= R.uniform

-- Provide a seed for the PRNG and return a draw from the random sampler
runRandL :: Rand a -> [Word32] -> a
runRandL rand seeds = runRandV rand (V.fromList seeds)

-- Provide a seed for the PRNG and return a draw from the random sampler
runRandV :: Vector v Word32 => Rand a -> v Word32 -> a
runRandV rand seeds =
  runST $ R.initialize seeds >>= runReaderT rand

-- Seed the PRNG with data from the system's fast source of pseudo-random numbers,
-- then return a draw from the random sampler
runRandIO :: Rand a -> IO a
runRandIO rand = do
  gen <- R.createSystemRandom
  seeds <- R.fromSeed <$> R.save gen
  return $ runRandV rand seeds

If you have f :: Rand a and you want n independent draws from f, then use replicateM f :: Rand [a] or V.replicateM f :: Rand (V.Vector a). The following example returns a draw from the sum of n independent uniform random variables:
sumOfUniform :: Int -> Rand Double
sumOfUniform n = do
  xs <- replicateM n uniform01
  return $ sum xs

The statistics package provides various data types that correspond to common statistical distributions. For example, normalDistr mu sigma :: NormalDistribution is an object representing a normal distribution; it contains the parameter values mu for the mean and sigma for the std deviation.
Instances of type class ContDistr d provide density and inverse CDF (quantile) functions for objects of distribution type d.
Instances of type class ContGen d provide a genContVar function for drawing from a continuous distribution, and instances of type class DiscrGen d provide a genDiscrVar function for drawing from a discrete distribution.
To make all of this easy to use with the Rand monad, I define some wrappers:
-- Draw from the continuous distribution d
genContV :: ContGen d => d -> Rand Double
genContV d = ask >>= genContVar d

-- Draw from the discrete distribution d
genDiscrV :: DiscreteGen d => d -> Rand Int
genDiscrV d = ask >>= genDiscreteVar d

-- Draw from the continuous distribution d using the inverse CDF method.
genCont :: ContDistr d => d -> Rand Double
genCont d = ask >>= genContinuous d

-- Draw from the normal distribution with mean mu and std dev sigma
normal :: Double -> Double -> Rand Double
normal mu sigma = genContV $ normalDistr mu sigma

Wrappers for other distributions (exponential, beta, gamma, etc.) follow the same pattern as the wrapper for normal distributions.
As a final example, here is a draw from the product of two normally-distributed random variables:
productOf2Normals :: Double -> Double -> Rand Double
productOf2Normals mu sigma = do
  x1 <- normal mu sigma
  x2 <- normal mu sigma
  return $ x1 * x2


text:
Q: Elasticsearch search API does not return results when called with document type I am trying to retrieve data from ES using the search API.
The name of the index is index_certificate and the document type is doc_certificate.
Below API call works fine and returns results.
curl -X POST "http://elasticsearch:9200/index_certificate/_search?pretty" -H 'Content-Type: application/json' -d'
{
  "query": {
    "bool": {
      "must": [
        {
          "match": {
            "district_id": {
              "query": "10"
            }
          }
        }
      ]
    }
  }
}'

But if I add the document type to the url without changing any other thing as below, it returns an empty result array. (Does not throw any errors)
curl -X POST "http://elasticsearch:9200/index_certificate/doc_certificate/_search?pretty" -H 'Content-Type: application/json' -d' { "query": { "bool": { "must": [ { "match": { "district_id": { "query": "10" } } } ] } } }'

I am not the one who did setup the node. Also this is not a production node. I am not sure whether this can be due to a read/write permission issue related to the document. I appreciate if someone can help me to solve this. Thank you.

A: As you can see the _type of your documents is _doc and not doc_certificate
So the following would work:
curl -X POST "http://elasticsearch:9200/index_certificate/_doc/_search?pretty" -H 'Content-Type: application/json' -d' { "query": { "bool": { "must": [ { "match": { "district_id": { "query": "10" } } } ] } } }'


text:
Q: Posting form data to API - all data formatted into URL I need to send form data to an API upon submission of the form. The API accepts the data in the URL itself.
For example, a URL should look something like this...
"http://client_server&function=add_lead&phone_number=07875582533&title=Mr&first_name=Nicholas&last_name=Dunk&phone_number=07574657463"
The phone number and name etc are generated from the form.
If I copy the API URL into the browser with form data I get a simple "SUCCESS: Lead has been added" response, so I know it's working.
I'm fairly new to JS so I don't really know how to go about doing this. I've tried using a $.get() request, but it gives me a "No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin null is therefore not allowed access" error.
I understand that this is a cross origin request, so I tried a jsonp request but this gives me an "uncaught syntax error: unexpected identifier" error. This only occurs if the datatype is changed to jsonp, so I assume it has some issue with the ?callback=?... that's added for jsonp.
The only other solution I have come up with is to open the URL in a new window on submission of the form, and then immediately close it again with JS, but this is not an ideal solution.
Can anyone help?
Thanks


text:
Q: Why are the tasks not being distributed to all the workers? The following in translated from the Divide and Conquer example in the ZeroMQ guide.
module ZeroMQ

open System
open System.IO
open System.Threading
open System.Threading.Tasks
open NetMQ
open NetMQ.Sockets

let parallel_task () =
    let task_number = 100
    let uri_source, uri_sink =
        let uri = "ipc://parallel_task"
        Path.Join(uri,"source"), Path.Join(uri,"sink")

    printfn "%A, %A" uri_source uri_sink

    let rnd = Random()
    use source = new PushSocket(uri_source)
    use sink = new PushSocket(uri_sink)
    let tasks = Array.init task_number (fun _ -> rnd.Next 100+1)

    let ventilator_init () =
        printf "Press enter when workers are ready.\n"
        printf "Total expected time: %A\n" (TimeSpan.FromMilliseconds(Array.sum tasks |> float))
        Console.ReadLine() |> ignore

    let ventilator_run () =
        sink.SendFrame("0")
        printf "Sending tasks to workers.\n"
        Array.iter (string >> source.SendFrame) tasks
        Thread.Sleep(1)

    let worker i () =
        printf "Starting worker %i\n" i
        use source = new PullSocket(uri_source)
        use sink = new PushSocket(uri_sink)
        while true do
            let msg = source.ReceiveFrameString()
            printf "Worker %i received message.\n" i
            //printf "%s.\n" msg
            Thread.Sleep(int msg)
            sink.SendFrame("")

    let sink () =
        use sink = new PullSocket(uri_sink)
        let watch = Diagnostics.Stopwatch()
        for i=1 to task_number do
            let _ = sink.ReceiveFrameString()
            if watch.IsRunning = false then watch.Start()
            printf (if i % 10 = 0 then ":" else ".")
        printf "\nTotal elapsed time: %A msec\n" watch.Elapsed
    ventilator_init()
    for i=1 to 4 do Task.Run (worker i) |> ignore
    let t = Task.Run sink
    ventilator_run()
    t.Wait()

[<EntryPoint>]
let main argv =
    parallel_task()
    0

What happens here is that a single worker gets all the messages and none of the other threads get assigned any work. Why is this happening?

A: open System
open System.IO
open System.Threading
open System.Threading.Tasks
open NetMQ
open NetMQ.Sockets

let parallel_task () =
    let task_number = 100
    let uri_source, uri_sink =
        let uri = "ipc://parallel_task"
        Path.Join(uri,"source"), Path.Join(uri,"sink")

    let ventilator () =
        let rnd = Random()
        use source = new PushSocket()
        source.Bind(uri_source)
        use sink = new PushSocket()
        sink.Connect(uri_sink)
        let tasks = Array.init task_number (fun _ -> rnd.Next 100+1)
        printf "Press enter when workers are ready.\n"
        printf "Total expected time: %A\n" (TimeSpan.FromMilliseconds(Array.sum tasks |> float))
        Console.ReadLine() |> ignore
        sink.SendFrame("0")
        printf "Sending tasks to workers.\n"
        Array.iter (string >> source.SendFrame) tasks
        Thread.Sleep(1)

    let worker i () =
        printf "Starting worker %i\n" i
        use source = new PullSocket()
        source.Connect(uri_source)
        use sink = new PushSocket()
        sink.Connect(uri_sink)
        while true do
            let msg = source.ReceiveFrameString()
            printf "Worker %i received message.\n" i
            Thread.Sleep(int msg)
            sink.SendFrame("")

    let sink () =
        use sink = new PullSocket()
        sink.Bind(uri_sink)
        let watch = Diagnostics.Stopwatch()
        for i=1 to task_number do
            let _ = sink.ReceiveFrameString()
            if watch.IsRunning = false then watch.Start()
            printf (if i % 10 = 0 then ":" else ".")
        printf "\nTotal elapsed time: %A msec\n" watch.Elapsed

    Task.Run ventilator |> ignore
    for i=1 to 4 do Task.Run (worker i) |> ignore
    Task.Run(sink).Wait()

Here is the cleaned up version of the above that works properly. I had to explicitly note what is a bind and what is a connection. Thank you @somdoron for the hint.


text:
Q: sap .net connector 3.0 idoc processing I need to implement Idoc processing with SAP .net connector 3.0
I'm looking for C# exemples. I didn't find any help into SAP .net connector 3.0 library: SAP.Middleware.Connector !!! Amazing: no reference at all on IDOC implementation !
old classes used in SAP .net connector 2.0 (such as SAPIDocReceiver) seem to have been removed from this new version.
i heard about 'IDOC_INBOUND_ASYNCHRONOUS' method (or class ?) which should be used in  SAP .net connector 3.0 ?
thanks to all, any help appreciated

A: You might consider to act as a RFC Server in NCO 3.0 and handle either 'IDOC_INBOUND_IN_QUEUE' and/or 'IDOC_INBOUND_ASYNCHRONOUS'.
[RfcServerFunction(Name = "IDOC_INBOUND_IN_QUEUE")]
public static void IDOC_INBOUND_IN_QUEUE(RfcServerContext serverContext, IRfcFunction rfcFunction)
{
    //Create table to handle control records
    IRfcTable irtControl = rfcFunction.GetTable("IDOC_CONTROL_REC_40");

    //Create table to handle data records
    IRfcTable irtData = rfcFunction.GetTable("IDOC_DATA_QUEUE");

    //Process tables
    //

    //Confirm receipt of IDoc
    //BAPI call back to SAP to confirm if needed
}

This site may be of value http://www.dataxstream.com/


text:
Q: Office 2010 - I can't open multiple documents at once? Is it just me or did Office 2010 remove the ability to open multiple documents at once?
I'm not talking about documents of the same type, I'm trying to open different types of documents (spreadsheets, word docs, powerpoints) but it doesn't work. However, opening documents of the same type works fine...
Anyone else have this problem? Is it truly gone or do I have a problem?
*Edit - To clarify, I mean open documents in Windows Explorer, by pressing the enter key or through the context menu.

A: You mean from the context menu in Windows Explorer? Nope, doesn't work here eighter. It would be possible if you decide to write your own Windows shell extension, but this would be another story.


text:
Q: Google map universities location I need to get the location information of universities, I just managed to get information about school.
But I want to see just universities. How can I do that?
 {
        "featureType": "poi.school",
        "elementType": "all",
        "stylers": [
            {
                "visibility": "on"
            }
        ]
    },

A: Google doesn't offer universities in their style references.
But if you need access to location information, maybe it is useful for you to use the Places API. It definitely offers you the option to filter places by type "university".


text:
Q: Puppet generating variables inside script I'm migrating a set of bash scripts that deploy a server to Puppet. Almost all of the functionality has been moved into Puppet, but I can't see how to migrate one bit of the bash script that does the following:

*

*Install PHP.

*With a PHP script, generate a random password and store it as a variable in the bash script.

*Use that variable elsewhere in the bash script to set the MySQL root password.

How can I set a puppet variable dynamically like this?
btw I'm using Puppet in a standalone version using puppet apply as I don't have a separate server to act as the puppet master.
Also, in case anyone is wondering why it's done like this, it's so that the MySQL root password doesn't exist anywhere except on the box where it's used and isn't written to any (readable) files.

A: You can just use the function "generate" in your manifest to call some kind of random string generator (pwgen?) and assign this value to a variable:
https://puppet.com/docs/puppet/3.8/function.html#generate

A: It looks like this is not feasible to do with Puppet running in standalone version.
All the variables inside classes are calculated when the scripts are read by Puppet, and so there is no way to make a dependency chain to:

*

*Install PHP.

*Call a PHP script to generate a value.

*Use the value.

In that order.
Theoretically it may be possible to use [run stages][1] to control this dependency, but these are not usable if your classes are includeed into the project, and so aren't recommended to be used ever.
As I have use a bootstrap script to install Puppet, I may as well just install PHP through the bootstrap script, rather than having Puppet manage it.