Feature branch is 1 commit behind Master after merging Hotfix branch to both

Question: I am new to git branches, so this question must be silly:
I have a master branch and a feature branch. I've created a third hot-fix branch, made some changes, and merged it to master. Afterwards, I also merged it to feature, because I am doing a lot of work there and I want the bugs fixed there as well.
Now, GitHub says that my feature branch is 1 commit behind the master, where this one commit is the pull request hot-fix->master, even though in reality both branches are identical in terms of the hot-fix changes because I also pulled them into feature
How should I be merging hot-fix branches to both master and feature without the latter being falsely behind?
Comment: You should have merged the `hot-fix` into `master`, then pulled(or rebased) `master` into `feature`
Comment: @nullptr what is "rebased"? If you mean pull master into feature, then I don't think its a good idea, because master can have many commits which I do not need in the feature branch. Am I misunderstanding?
Comment: you will eventually merge `feature` into `master`, right? then what is the issue of having those commits in `feature`? if you don't want to pull `master` into `feature`, then you can try `git cherrypick` to pick only the `hot-fix` merge commit from `master` into `feature`
Comment: There's normally no reason why you wouldn't merge master into your feature if it has changes you want. This is a standard part of most git work flows (such as git flow) - If things are in master then they are meant to be good enough to use.
In git flow you would merge the `hot-fix` into `master`, then to get that change into your feature branch merge `master` into `feature`. If you want to keep the history clean you could rebase instead but I recommend getting to grip with merging before rebasing or it'll be even more confusing,
Answer: You're one commit behind because there's one commit that's "on" master that is not on your branch.  That's no big deal.  Well, you'll find lots of opinions about what is or is not a big deal, how you should work, and so on.  Some will contradict others.  You can pick any plan that works and stick with it, or hopscotch around with various things that work: whatever works, works.  It might be confusing to others though, which might make it stop working in a different sense.
Instead of getting all caught up in right-flow / wrong-flow arguments, let's just look at what you did and why you see the result you see.  You can choose your eventual course later, once you understand the building blocks.

I have a master branch and a feature branch. I've created a third hot-fix branch, made some changes, and merged it to master. Afterwards, I also merged it to feature, because I am doing a lot of work there and I want the bugs fixed there as well.

Git isn't really about branches, and in a way, branch is a bad word—not in the sense of being explicit or foul language or something, but rather, in the sense that it fails to communicate the right meaning.  The problem is that the word branch in Git has at least two different meanings, and probably more: exactly how many will depend on what and how you go about counting.  (See also What exactly do we mean by "branch"?)
What Git is really about, in the end, is the commit.  A repository is a collection of commits—all stored in a big database, indexed by hash IDs or more formally object IDs or OIDs—plus some other stuff, which is important, but let's concentrate on the commits first.  Each commit is numbered: it gets a unique, but random-looking and very large and unwieldy, number, which Git insists on spelling in hexadecimal, as, e.g., 4af7188bc97f70277d0f10d56d5373022b1fa385.  In theory, the number alone suffices to find the commit, because the number is totally unique.  Any Git repository that has a commit with that number has exactly that commit.1  In practice, we have to have the repository already, and then we can ask it for that commit, by the hash ID: if it isn't in there, we pick some other repository that does have it and use git fetch to get it from the other repository.
So, in short, we use the commits in the repository, as that's what the repository is about.  We ask for them by raw hash ID; Git pulls them out.  Each commit holds two things:

A commit holds a full snapshot of every file as of the state it had when it got frozen into that commit, as an archive.  These are the files we want to use / work-with.  They're in a special, read-only, Git-only format, compressed and—importantly—de-duplicated, so that the repository doesn't fatten up grotesquely as we add commit after commit.  Only changed files need to be stored, and even then they can be stored very efficiently (with further tricks happening eventually, long after the initial de-duplication).

A commit also holds some metadata, or information about the commit itself.  This includes things like the name and email address of the person who made the commit, and date-and-time stamps, and so on.

1Some simple math, specifically the pigeonhole principle, tells us that this cannot work forever.  The sheer size of the hash space is meant to put off the inevitable Git failure for billions of years, though the birthday problem or birthday paradox means it can't work even as long as that.  But if it works until after we're all dead and gone, that's probably long enough. That's someone else's problem!

Commits form branches
Crucially for Git itself, Git stores the raw hash IDs for a list of previous commits in any new commit anyone ever makes, in the metadata for the new commit.  The commits themselves are entirely read-only—this is required by the magic hash ID numbering system—so no part of any commit can ever change, and each commit records one—well, zero or more, but usually just one—previous commit hash ID.  This forms a backwards-looking chain, where, if we just know the hash ID of the latest commit, we can have Git find all the earlier commits.
Let's call the latest commit hash ID H (for "hash"), and draw the commit:
            <-H

We draw the commit with an arrow sticking out of it, pointing backwards, to represent the stored hash ID in H.  Let's call that hash ID G for short and draw commit G too:
        <-G <-H

Of course, G has another arrow sticking out of it: G's metadata stores the raw hash ID of some earlier commit.  Let's call that one F and draw it in too:
... <-F <-G <-H

The result is a chain that goes back all the way through history, until it reaches the very first commit ever.  If we call that commit A, and draw it in, commit A has no backwards arrow: its list of previous commits is empty.  This is kind of a special case, but it simply means "there's no previous commit", which allows Git to stop going backwards:
A--B--...--G--H

We'll get lazy (for various reasons good and bad) and stop drawing the internal arrows here as arrows.  Inside Git, they point backwards—and it's important to remember that now and then—but humans really like to go forwards a lot, so a diagram like this is OK, and easier to draw (i.e., I'm a little lazy ).  The point here is to note that all we need is to somehow (magically?) find commit H.  From there, Git can find every earlier commit.
Branch names find branches
We could memorize the actual latest hash ID.  We'd have to memorize a new, big ugly hash ID every time we make a new commit, though.  We could write them down on paper, and carefully type them in to Git commands, but that seems stupid ... and, wait!  We have a computer!  Let's make it remember these hash IDs for us!  What if we dropped the latest hash ID into a file ... no, better, a database of branch names?
And that's exactly what we do: a repository has, besides the database of commit objects and other internal Git objects that's indexed by raw hash IDs, a database—usually much smaller—containing branch and tag and other such names.  Each name holds just one hash ID, but that's all it takes:
...--G--H   <-- master

The name master literally holds the hash ID for commit H.  So now we can just run:
git log master

and view commits from H on backwards, as Git follows H back to G, then to F, and so on, backwards.
We can, at any time, tell Git to add new names.  We can also tell Git to delete names.  The names simply point to a commit: there is one arrow coming out of each name, pointing to any commit we like.
If we create a new branch name feature right now, we have to pick one of our commits, to make the name point to that commit.  We can pick H, or G, or anything earlier.  But let's pick H—the latest commit—because why would we pick an earlier one?  We get this:
...--G--H   <-- feature, master

Both names point to commit H.  That's perfectly fine.  But that leaves us with a couple of questions:

How do we know which name we're actually using?  To answer that, Git attaches a special name, HEAD, written in all uppercase like this, to one and only one branch name.

Which branch are these commits on?

The second question is a trick question, because these commits are actually on both branches.  What it means, in Git, for a commit to be "on" some branch, is that we can find that commit by starting with the commit to which the branch name points and working backwards.
So, with:
...--F--G--H   <-- feature (HEAD), master

we know that we're "on" branch feature, and that this branch contains commits up through and including H.  Branch master also contains the same commits.
Making new commits drags the current branch name forward
If we now make a new commit, in the usual way—we'll skip right over what that is since you already know it—this new commit will get a new unique hash ID.  Let's call that hash ID I.  Commit I will point back to existing commit H, like this:
...--G--H
         \
          I

I drew new commit I on a new line, because Git's last trick, as it creates new commit I and thereby obtains the new unique hash ID, is to store that ID into the current branch name.  The current branch name is the one that has HEAD attached to it.  The other branch names—no matter how many there are—don't change at all during this update, so now we have:
...--G--H   <-- master
         \
          I   <-- feature (HEAD)

Putting some pieces together
Let's go back to your original statement:

I have a master branch and a feature branch. I've created a third hot-fix branch, made some changes, and merged it to master. Afterwards, I also merged it to feature, because I am doing a lot of work there and I want the bugs fixed there as well.

Each of these names must, necessarily, point to one single commit.  Which one?  I have no idea: that's in your repository, which I don't have.  I'll make something up, with the caveat that my made-up example obviously won't match your own repository exactly.  Here's my made-up example:
          E  <-- release/1.0
         /
...--C--D--F--G   <-- master
               \
                H   <-- feature (HEAD)

Now, to fix the bug, which was in commit D, we've checked out commit D and attached a branch name there, hot-fix:
          E  <-- release/1.0
         /
...--C--D   <-- hot-fix (HEAD)
         \
          F--G   <-- master
              \
               H   <-- feature

and then we fix the bug, making a new commit I:
          E  <-- release/1.0
         /
...--C--D--I   <-- hot-fix (HEAD)
         \
          F--G   <-- master
              \
               H   <-- feature

We can now merge commit I, the hot-fix for the bug in D, into any of these various branches.  (That's the advantage to going back in time and fixing the bug as soon as it got introduced: it's always possible to "forward merge" the fix.  Not everyone uses this method, as it brings a certain amount of pain as well, but without any better guide to drawing your situation, it's what I'm drawing.)
Merging in Git
Note: I'm moving fast here, skipping over a lot of helpful introductory material.  For instance, I've skipped how Git transforms a commit, which is a snapshot, into a diff or patch or changeset, which isn't.  For a gentler introduction, consider a longer tutorial, or one of my other answers.
Merging in Git is about combining changes.  Sometimes there's nothing to combine, which makes things easier, but I've carefully made sure that there's always something to combine in these examples, so that we'll go through only the most general case.
Ignoring the other diagrams so far, let's look just at this particular diagram:
          I--J   <-- br1
         /
...--G--H
         \
          K--L   <-- br2

We'll pick one of the two branches and use git switch or git checkout to make it the current branch and hence make J or L the current commit.  For simplicity (and because the merge result is symmetric in most practical cases anyway) let's just pick br1.  Then we'll run git merge and give it the other branch name, which Git will use to find the other of the two commits—i.e., commit L.
To perform the actual work of merging, Git must now find the common starting point.  Git does this on its own, using the graph implied by the parent links.  That is, Git works backwards from the current commit J to find I and H and so on.  At the same time, Git works backwards from the other commit we named: L leads back to K, which leads back to H.
It's obvious from this drawing that the first shared commit, on both branches, is commit H.  (Or is that the last shared commit?  Depends on whether you think backwards, like Git does, doesn't it?)  Anyway, skipping over lots more potential complexities that don't occur in carefully chosen examples like this one, commit H is our merge base, or common starting point here, for git merge.
To combine work, what Git does now is to run git diff on (i.e., compare the snapshots in) commits H and J, to see what we did on branch br1, and then, separately, diff commits H and L, to see what they (whoever "they" are) did on branch br2.  For each file, this gives us "what changed", and the changes apply to the same starting point because there's just the one copy of that file in H, and the one copy in each of the two targets.  That makes it easy for Git to combine the two sets of changes.  Each change is either adding or deleting some lines, because that's what comes out of git diff internally.
Having combined the changes—taken the "ours" (H-to-J) changes and the "theirs" (H-to-L) changes—for any one particular file, Git then applies both changes to the copy of the file from the base commit, H.  Where (if) two changes overlap, Git requires that they be exactly the same change, otherwise Git declares a merge conflict and forces you—the programmer—to fix things up.  (This description omits a number of special cases, but covers the majority of what Git does for you.)
If Git is able to combine all the changes to all the various changed files, and apply those combined changes to all the files from the merge base commit, Git will go on to make a new commit.  This new commit is special in exactly one way: instead of listing one previous commit, it lists two.  That's all!  Like every other commit, this new commit has a snapshot and metadata: the snapshot stores all the files, in their merged form, and the metadata shows that you made this commit, just now.  The only thing special about this new commit is that it links back to both commits J and L, like this:
          I--J
         /    \
...--G--H      M
         \    /
          K--L

As usual, Git writes the new commit's hash ID in the current branch name.  Since we said we made br1 the current branch, that means we finish off our drawing this way:
          I--J
         /    \
...--G--H      M   <-- br1 (HEAD)
         \    /
          K--L   <-- br2

Note how, at this point, the commits "on" br1 include commit M, and then—because M points back to both J and L—commits J and L, and I and K, and then H and G and so forth.  But when we use the name br2, the commits that are "on" this branch start at L, and go back to K, then H, then G and so on.  Git literally can't go forwards: commit H does not connect to either I or K.  All the connections are strictly backwards.
So commit M is not on br2, it's only on br1.  The same goes for I-J.  But merging like this has caused commits K-L, which were only on br2 before, to be on both branches now.
This is in fact the answer to your question, but to finish things off, let's look at the rest of the details.  There are often a bunch of complications in the way of seeing it.
Ahead and/or behind
Given any two branch names, Git can count how many commits one name is "ahead of" the other, and how many it is "behind", simply by counting the commits that we can only "see" on one of the two names:
...--F   <-- br1
      \
       G--H   <-- br2

Here, branch br2 is "two commits ahead of" br1 because commits up through F are on both branches but G-H are only on br2.  This in turn means that br1 is two commits behind br2.  When we have a "forking" or "branching" structure like this one:
          I--J   <-- br1
         /
...--G--H
         \
          K   <-- br2

we find that br1 is "ahead 2" and "behind 1" of br2, and br2 is "ahead 1 and behind 2" of br1.  These are precisely commits I-J(the two) andK` (the one).
Merging causes commits that weren't "on" some branch to be "on" the branch.  That branch is now "less behind", maybe not at all behind.  But making a new merge commit causes the branch that just acquired the new commit to be "ahead".
Note that if you draw the graph, a lot of these things get clearer.  You can do this by hand, or have Git and/or other programs do it.  See also Pretty Git branch graphs.
More questions
This is the whole answer to your question as asked, but there are a few more questions we should ask.  Let's look now at these.
You have a repository, local to you, where you do your work.  Let's call this "on your laptop" (whether or not your computer is a laptop computer) as this gives us a good name for it.
Meanwhile, GitLab has a different repository, stored on their server.  This other repository has its own databases.  The commits that are in their objects database, and the commits that are in your laptop Git's objects database, get shared: their unique hash IDs tell them apart, and when you and they have the same commit, you and they have a database entry whose key is that particular shared hash ID and the contents match.  (This database is a simple key-value store, with hash IDs as the keys.)  But—this is important—the branch names are not shared.  They have their names, and you have yours; each of their branch names holds one hash ID, and each of your branch names holds one hash ID.
When you ran git clone to make your laptop repository, your Git read, from their Git, all the commits and stuffed them into your new objects database, so that you had copies of all their commits.  But your Git took each of their branch names, like master, and changed them into remote-tracking names like origin/master.  Your Git software will copy their branch names into your repository by making this change, turning branch names into remote-tracking names.  This keeps your branch names yours.
The git fetch command has your Git reach out to their software, using the URL stored under the name origin.  Your Git has their Git list out their branch names and commit hash IDs.  Your Git can immediately tell if you have all their commits or not, just by checking those hash IDs.  For any commits you are missing, your Git will ask their software to package up those commits and send them over, and it will do that.  Those commits come with the parent commits, up until the point where your Git already has the commit(s) needed, so that you get all their new commits that they have that you don't.  Then your Git will update all your remote-tracking names to remember their new most-recent-commits for each branch (what Git calls a tip commit, whether it's a branch tip or a remote-tracking-name tip).
If you run:
git status

you will see an "ahead" and/or "behind" count for the upstream of your (local) branch, which is typically the corresponding remote-tracking name in their repository.  So you run:
git fetch

(or git fetch origin) to update your repository with any new commits they have that you don't, and update all your origin/* names to remember the tip commits of their branches, and then git status tells you about your branch foo with respect to their origin/foo, assuming the upstream of your foo is origin/foo.
To send commits to them you use git push.  This is as close as Git gets to the opposite of git fetch, but it has some key differences.  As before, your Git calls up their software at the stored URL.  You (or your Git) then offer to them a commit hash ID: usually, the tip commit of one of your branches.  If they don't have that commit yet, your Git software has to offer the commit's parent(s), just like for git fetch, until you and they find the shared commits that you don't need to re-send; you then send all these commits.  But then, instead of having them set a "remote-tracking name" in their names database, your Git will ask—politely, by default—that they change one of their branch names to remember this as their new tip commit for that branch.
That is, you don't say to them: "Here's some new commits, remember them under grant/master" but rather: "Here's some new commits, now please set your own master` to remember the tip commit as its latest tip commit."  In other words, you'd like them to add commits to their branch.
GitHub, GitLab, and other hosting providers all add various protection features so that not anybody can add commits—base Git has no permissions checking!—but assuming you have permission and you're just adding new commits, they generally do as you ask.  In any case, whether or not they permit this update, they send back a response: OK, I set my branch or no, because ____ (fill in the blank).  The OK response makes your Git update your remote-tracking name, because they accepted the update.  The "no" makes your Git produce a "rejected" error, using the filled-in-blank.
The most common error (besides the permission-denied type errors that hosting sites add) is "non-fast-forward", which is Git's peculiar way of saying: I can only remember one hash ID in a name, and if I make this change, some commits that I can access right now via that name, will no longer be find-able via that name.
Since you'll generally view ahead/behind through the lens of "these pushes worked and updated my remote-tracking names" or "I just ran git fetch and updated my remote-tracking names", what you see here is often a single or double level reflection of what you've done in your own repository.  This makes for a bit of confusion sometimes.  But if we take the repository I drew early on above:
          E  <-- release/1.0
         /
...--C--D--I   <-- hot-fix (HEAD)
         \
          F--G   <-- master
              \
               H   <-- feature

and then add merge commits as appropriate:
git switch master && git merge hot-fix

          E  <-- release/1.0
         /
...--C--D--I___  <-- hot-fix
         \     \
          F--G--J   <-- master (HEAD)
              \
               H   <-- feature

(new commit J on master) and:
git switch feature && git merge hot-fix

          E  <-- release/1.0
         /
...--C--D--I______  <-- hot-fix
         \     \  \
          F--G--J  \  <-- master
              \     \
               H-----K   <-- feature (HEAD)

(the diagrams get messy, but here's new merge K on feature) we can see that feature is now "ahead of" master because commit K isn't on master.  That's true even if we just merge feature into master instead:
git switch feature && git merge master

produces:
          E  <-- release/1.0
         /
...--C--D--I___  <-- hot-fix
         \     \
          F--G--J   <-- master (HEAD)
              \  \
               H--K   <-- feature

It's the new merge on feature, commit K, that pushes us "ahead of" master every time.
(Git has a non-merge-y kind of operation that Git calls—misleadingly—a fast-forward merge, that git merge can perform, that doesn't make a new merge commit.  It can only be used in particular circumstances and GitHub in particular will never do this, no matter how much you might want them to; GitLab may differ here.  But presumably this is not what you're doing, or you would not have had this question!  I skipped over it in the merge section for space reasons.)


filter by Sum without Grouping

Question: i have a resultset that i generate from a query that Looks like this:
  Select Employee, Month, (select case when Status = '---' then 0 Else 1 end) as PlaningValue
  From   PlanningTable PT
  Where  Month >= @From Month and Month <= @ToMonth

The Result of this Looks something like this:
|Employee|  Month  | PlaningValue |
|George  | 2014-01 |            1 |
|George  | 2014-02 |            1 |
|George  | 2014-03 |            0 |
|Andrew  | 2014-01 |            0 |
|Andrew  | 2014-02 |            1 |
|Andrew  | 2014-03 |            0 |
|Howard  | 2014-01 |            1 |
|Howard  | 2014-02 |            1 |
|Howard  | 2014-03 |            1 |

Now what i want is the following:
Filter out Employee's who, over the three month period, have a total planing Value of 3,
in the example above, Howard would be filtered out.
Is there a way to do this nicely or is it all just impossible to even thin ?
(Remark: Since i am going to use the Query on Reporting Services, i can't use the OVER function)
Thank you all for your help
Comment: Weird CASE syntax. Why you selecting it?
Answer: This looks to be SQL Server syntax, as such I you can use windowed functions:
WITH CTE AS
(   SELECT  Employee,
            Month,
            PlanningValue = CASE WHEN Status = '---' THEN 0 ELSE 1 END,
            Total = SUM(CASE WHEN Status = '---' THEN 0 ELSE 1 END)
                        OVER (PARTITION BY Employee)
    FROM    PlanningTable
    WHERE   Month >= @FromDate
    AND     Month <= @ToMonth
)
SELECT  Employee, Month, PlanningValue
FROM    CTE
WHERE   Total != 3;

Simplified Example on SQL Fiddle
Comment: I think the OP wants `WHERE Total <> 3`
Comment: Thanks for the Answer,
the issue i am having now is that i am not able to Unionize the Results with another query, i have added a semicolon to make the above answer work before WITH,
but i can't UNION the results with another query i have, is there something i can do ?
Comment: and i have just realised that i can't use windowed functions in Reporting Services
It says the OVER function is not supported
Comment: SSRS does support the use of OVER, although the comment beneath [this answer](http://stackoverflow.com/a/9034758/1048425) would indicate SSRS query studio can cause errors with it. There is no reason you shouldn't be able to use UNION with a CTE, the CTE just has to come first, but if it is a problem just move it to a subquery - [Demo on SQL Fiddle](http://sqlfiddle.com/#!3/fd13d/8)
Answer: Try:
select pt.employee, pt.month, pt.planningvalue
from planningtable pt
   join planningtable pt2 on pt.employee = pt2.employee
   join planningtable pt3 on pt.employee = pt3.employee
   join planningtable pt4 on pt.employee = pt4.employee
where month >= @mofrom and month <= @tomonth
   and pt2.month = @tomonth
   and pt3.month in (select month from planningtable where month > @mofrom and month < @tomonth)
   and pt4.month = @mofrom
   and pt2.planningvalue + pt3.planningvalue + pt4.planningvalue <> 3

filter by Sum without Grouping


Frigidaire FRS23R4CW2 fridge no defrost?

Question: we have a Frigidaire FRS23R4CW2 refrigerator manufactured in 2010.  Has been working well until a few weeks ago.  This is a side-by-side unit with freezer on the left.
Noticed the icemaker was not making ice.  Then noticed the freezer section is warmer than normal.  Finally got to the point where food is barely frozen.
Google says one of the more common causes of this problem is a failed evaporator fan motor.  However, I can hear the fan running at full speed when I open the freezer door.
Removed the freezer shelves and the back panel.  The evaporator was completely clogged with ice.
Unplugged the fridge and let it sit overnight with towels in the bottom to capture excess moisture.  There was still some ice at the bottom of the evaporator, so used a hair dryer on the lowest heat setting to get rid of it.
Plugged the fridge back in and stuck a thermocouple in the evaporator.  Refrigeration cycle is working well - evap coil got down to -24C in a few minutes.
The wiring diagram for this model says that the unit has an electronic defrost control. The procedure to invoke a manual defrost is to operate the light switch on the fridge side 5 times within 6 seconds.  I did that but do not see any signs of defrost action.  I'm using both a non-contact AC probe (Fluke LVD2) and checking at the defrost heater as well as the defrost termination temp snap switch clipped to the top tube of the evaporator.  Tried this several times.
Clip-on AC ammeter also shown no defrost current.
The evap coil is currently sitting at about -43C and is accumulating ice.  I'm leaning towards suspecting the refrigerator control board but would greatly appreciate advice on other things I can check.
Comment: I see several possible problems. Is the condenser clean and the fan operating properly. If that is so I would say it appears you could also have a slight loss of refrigerant, this would take a pro to confirm.
Comment: Loss of refrigerant might easily occur in an 11-year-old unit.
Comment: I think that you missed what I mentioned for symptoms.  1) No defrost current.  2) evap coil sitting colder than -40.  That said - comments and suggestions greatly appreciated!
Answer: Problem turned out to be the "Adaptive Defrost Control" module.  There are two electrolytic caps on the board.  The larger of the two (1000uF / 10V) had the classic bulged top.  I replaced that capacitor and checked both the value and ESR of the other capacitor (22uF / 100V) - seems to be okay.  I would have replaced it as well but that isn't a value that we stock.  But it seems okay.
Fridge has been running for only a short time but long enough for the evaporator to get down to -20.  I triggered a manual defrost and it seems to be working.
You can see the bulging top of the cap to the left of the blue rectangular film cap.  Replaced it with a Sanyo 1000uf / 16V (very) low ESR capacitor that we use in switch mode power supplies.
I also took the opportunity to test the relay - both NC & NC contacts.  It's a DPDT relay and all 4 contacts were less than 10 milliohms each.


In android : how to make strings inside Listview enable copying

Question: public class mychatorderdetails extends ActionBarActivity {
    private MyApplication app;
    private String order_id;
    private String orderdate;
    private String cust_name;
    private String cust_address;
    private String cust_pincode;
    private String cust_mobile;
    private String action;
    private String UPI;
    private Button bt;
    private OrderDetailsAdapter oa;
    private ListView lv;
    private ArrayList<HashMap<String, String>> messageList;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_mychatorderdetails);
        getSupportActionBar().setDisplayHomeAsUpEnabled(true);

        messageList = new ArrayList<HashMap<String, String>>();
        app=((MyApplication) getApplicationContext());

        Bundle extras = getIntent().getExtras();

        if(extras != null) {
            order_id = extras.getString("order_id");
            orderdate = extras.getString("orderdate");
            cust_name = extras.getString("cust_name");
            cust_address = extras.getString("cust_address");
            cust_pincode = extras.getString("cust_pincode");
            cust_mobile=extras.getString("cust_mobile");
            UPI=extras.getString("UPI");
            action=extras.getString("action"); //setaccepted, setdelivered
        }

        bt = (Button) findViewById(R.id.btnAction);
        switch (action)
        {
            case "setdelivered":{
                bt.setText("Delivered");
                break;
            }
            case "setaccepted":{
                bt.setText("Accept");
                break;
            }
            default:
        }

        try {
            String dpart = orderdate.substring(0, 10);
            String tpart = orderdate.substring(11, 19);
            orderdate = dpart.substring(8,10);
            orderdate+="/"+dpart.substring(5,7);
            orderdate+="/"+dpart.substring(0,4);
            orderdate+=" "+tpart;
        }
        catch (Exception e)
        {
            Log.d(getString(R.string.app_name), e.getMessage());
        }
        HashMap<String, String> row = new HashMap<String, String>();
        row.put("type", "text");
        row.put("details", "Order ID:"+order_id);
        messageList.add(row);
        HashMap<String, String> rowd = new HashMap<String, String>();
        rowd.put("type", "text");
        rowd.put("details", "Order Date:"+orderdate);
        messageList.add(rowd);
        HashMap<String, String> row1 = new HashMap<String, String>();
        row1.put("type", "text");
        row1.put("details",cust_name);
        messageList.add(row1);
        HashMap<String, String> row2 = new HashMap<String, String>();
        row2.put("type", "text");
        row2.put("details",cust_address);
        messageList.add(row2);
        HashMap<String, String> row3 = new HashMap<String, String>();
        row3.put("type", "text");
        row3.put("details","Pin:"+cust_pincode);
        messageList.add(row3);
        HashMap<String, String> row4 = new HashMap<String, String>();
        row4.put("type", "text");
        row4.put("details","Mob:"+cust_mobile);
        messageList.add(row4);
        HashMap<String, String> row5 = new HashMap<String, String>();
        row5.put("type", "text");
        row5.put("details","UPI:"+UPI);
        messageList.add(row5);
        oa=new OrderDetailsAdapter(mychatorderdetails.this,messageList);
        lv = (ListView) findViewById(R.id.lstOrderDetails);
        lv.setAdapter(oa);

        lv.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                try {
                    HashMap<String, String> temp = new HashMap<String, String>();
                    temp = messageList.get(position);
                    if(temp.get("type")=="image")
                    {
                        //Uri uri = Uri.parse(temp.get("details"));
                        showImage(temp.get("details"));
                    }

                } catch (Exception e) {
                    Log.d(getString(R.string.app_name), e.getMessage());
                }
            }
        });

        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                    try {
                        JSONArray det = app.getMyChatOrderDetails(order_id);
                        for (int i = 0; i < det.length(); i++) {
                            JSONObject cat = det.getJSONObject(i);
                            HashMap<String, String> row = new HashMap<String, String>();
                            if(!TextUtils.isEmpty(cat.getString("msg_image").toString()))
                            {
                                row.put("type", "image");
                                row.put("details",cat.getString("msg_image").toString());
                            }
                            else
                            {
                                row.put("type", "text");
                                String mfv=cat.getString("msg_for_vendor").toString();
                                if(mfv.equals("1"))
                                {
                                    row.put("details","Customer: "+cat.getString("msg_text").toString());
                                }
                                else{
                                    row.put("details","Me: "+cat.getString("msg_text").toString());
                                }

                            }
                            messageList.add(row);
                        }

                        oa.notifyDataSetChanged();

                    } catch (JSONException e) {
                        Log.d(getString(R.string.app_name), e.getMessage());
                    } catch (Exception e) { //connection timeout
                        Log.d(getString(R.string.app_name), e.getMessage());
                        Toast.makeText(getApplicationContext(), e.getMessage(), Toast.LENGTH_LONG).show();
                    }
            }
        });
    }

    public void showImage(String imageUri) {
        Dialog builder = new Dialog(this);
        builder.requestWindowFeature(Window.FEATURE_NO_TITLE);
        builder.getWindow().setBackgroundDrawable(new ColorDrawable(android.graphics.Color.TRANSPARENT));
        builder.setOnDismissListener(new DialogInterface.OnDismissListener() {
            @Override
            public void onDismiss(DialogInterface dialogInterface) {
                //nothing;
            }
        });
        try {
            ImageView imageView = new ImageView(this);
            Bitmap bitmap = BitmapFactory.decodeStream((InputStream) new URL(imageUri).getContent());
            if (bitmap != null) {
                imageView.setImageBitmap(bitmap);
                LinearLayout.LayoutParams layoutParams = new LinearLayout.LayoutParams(450, 400);
                imageView.setLayoutParams(layoutParams);
                imageView.setVisibility(View.VISIBLE);
                builder.addContentView(imageView, new RelativeLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT));
                builder.show();
            }
        }
        catch (Exception e)
        {
            Log.d(getString(R.string.app_name), e.getMessage());
        }
    }

    public void doAction(View v)
    {
        switch (action)
        {
            case "setdelivered":{
                if(app.setOrderDelivered(order_id)) {
                    Toast.makeText(this,"Order marked as delivered...",Toast.LENGTH_LONG).show();
                    bt.setVisibility(View.INVISIBLE);
                }
                break;
            }
            case "setaccepted":{
                if(app.acceptChatOrder(order_id)){
                    Toast.makeText(this,"Order accepted...",Toast.LENGTH_LONG).show();
                    bt.setVisibility(View.INVISIBLE);
                }
                break;
            }
            default:
        }
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.menu_mychatorderdetails, 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();

        Intent intent;
        //noinspection SimplifiableIfStatement
        if (id == R.id.action_logout) {
            app = ((MyApplication) getApplicationContext());
            app.logOut();
            intent = new Intent(mychatorderdetails.this, LoginActivity.class);
            intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_NEW_TASK);
            mychatorderdetails.this.startActivity(intent);
        }
        mychatorderdetails.this.finish();

        return super.onOptionsItemSelected(item);
    }
}

Following is the code to display my List ITEMS. I wanted my 5th row item i.e UPI to be enabled copying when long pressed on it. How do I do this? Please edit my code for the same to happen.
Answer: In your row_layout for your ListView, just add the property android:textIsSelectable to the TextView on which you want copying to be allowed.
Comment: I am not using a textview to display the list.i am using a list view to display the list
Comment: Can you share your OrderDetailsAdapter?
Answer: Change in layout file: add the below property to your TextView:
android:textIsSelectable="true"

OR
In your Java class write this line to set it programatically:
myTextView.setTextIsSelectable(true);

Copy text:
tv.setOnLongClickListener(new View.OnLongClickListener() {

    @Override
    public boolean onLongClick(View v) {
        ClipboardManager clipboard = (ClipboardManager) getSystemService(Context.CLIPBOARD_SERVICE);
        ClipData clip = ClipData.newPlainText("", tv.getText());
        clipboard.setPrimaryClip(clip);
        Toast.makeText(context, "Copied to clipboard", Toast.LENGTH_SHORT).show();
        return true;
    }
});

Make sure you have imported android.content.ClipboardManager and NOT android.text.ClipboardManager.
Comment: .I am not using a textview.i am using a listview to display this list
Comment: Your are using OrderDetailsAdapte class to show the list item.Set  android:textIsSelectable="true" in adapter class
Comment: That will make my text selectable only isnt it.I want to copy the text
Comment: On text longpress of textview use ClipboardManager
Comment: can you show me an example code to how to implement this
Comment: Thank you it worked.One more help I need.Now when it is copied we are unable to know whether its copied or not.how to give a message like text copied as soon as the text is copied.Thanks a lot for solving my issue
Comment: Give the toast message "text is copied" after clipboard.setPrimaryClip(clip); . Check updated code
Comment: can you please look into this link .this i s amian problem i am facing with my current app.if you can please provide a best solution


Flutter Responsive Grid with Cards (screenshots)

Question: I am very new to flutter and modern programming languages at all. At the moment I am working together with someone in order to create an app.
We are having problems with the layout of the grid and cards with different screen sizes and orientations.
Vertical Screen Screenshot
Horizontal Screen Screenshot
As you can see, the cards are messed up as soon as the screen width is too high. I don't have access to the source code right now, as the person programming it, is not available at the moment.
I read a lot about different techniques to build a card grid like that in a responsive way.
My guess the problem is, that the cards are not in containers with a fixed size. If they were, the pictures / buttons and texts inside that container would always look the same. Is that assumption correct?
Then my other idea was to use ResponsiveGridListBuilder to solve the problem that too few cards are shown in horizontal mode.
But as I said ... I am a newbie in flutter, so if any of you could make suggestions, I would be happy!
If possible, some code as an example would also help a bunch.
So far the programmer only tried different calculations of the cards in comparison to the screensize, but this didn't help as you can see.
Cheers!
Answer: I think it's better you use Wrap to fill the Row even in horizontal or vertical screens. but if i was in your shoes i would develop the items that are suitable and has const size for vertical and horizontal sizes, and let them to fill theirselves in the row depends on the width screen size that it has.
if you didn't understand what i mean i can explain it more my friend :)
happy coding...
Comment: Hi, thanks for the answer!
Do you mean you would basically define the different items with hardcoded values, for example a width of 400 and a specific spacing between the items and then check how many fit into the screen and create rows / columns accordingly?
Comment: I mean, create an item that has static size(even it rotates) and use Wrap widget. using wrap will fill that item according the size of that row or a column for example not just 3 items in one row. please search about Wrap and how it works and create that item with sizes that you rotate the screen it does not change the schema. and let it fill the items itself. if you had any question or did not find out, we can connect on google meet and i can explain it more.
Comment: Thanks, that is already a big help. I'll research about it! What you describe (the item rotates with identical size) is exactly what I am looking for.


cannot be sorted!

Question: i have few files let say setup.wxs, client.wxs and report.wxs. pratically, client.wxs and report.wxs each has its own <.FeatureRef Id="MainApplication"> to the main <.Feature Id="MainApplication" ...>. but the funniest thing is, i cannot sort the tree order.
let say i want:
MainApp
 |- Client
 |- Report
Unfortunately, it will come out the result with:
MainApp
 |- Report
 |- Client
unless i put these all features into the main setup.wsx without <.FeatureRef>. by this way, i can sort them as what i wanted.
can any help me on this?
Answer: Correct. If you want to control the order, then you need to put FeatureRef or Feature elements in the correct order under the MainApp Feature. Limitiation of the WiX toolset (that no one has complained about until now ;).
You could probably open a feature request against the WiX toolset.

cannot be sorted!


Using Qt without openGL

Question: I installed Qt on Ubuntu and when I try to comiple a project it reports error: cannot find -lGL. But I am having problem with installing openGL library so I wanna know if it is possible to use Qt without openGL, to somehow exclude that library from linking...
Comment: What exactly is the problem, if you try to install OpenGL development files? On Ubuntu it's as simple as executing `sudo apt-get install libgl1-mesa-dev`
Comment: I did sudo apt-get install libgl1-mesa-dev, but the problem is after I install it, my Ubuntu freezes and when I start it next time it stops at booting. Then I reinstalled Ubuntu and again after installing openGL it freezes and cant be started again...I run it on VirtualBox. Qt version is 5.
Comment: Are you asking "how do I remove the `-lGl` from the linker flags"? All the comments are on how to satisfy a dependency you don't need, or how to remove the ability to link against a library.
Answer: installed Qt on Ubuntu --> How..? Which Version? Did you configure it? You can configure it while installing, and if you do not want OpenGL you can just give option

-no-opengl

when I try to comiple a project it reports error: cannot find -lGL --> But if your project needs OpenGL, what is the point in having "No OpenGL"? you should rather install OGL development libraries(see datenwolf's comment) so that you can work on the project.
Comment: You normally install libraries from a package manager in Linux. That Qt `-no-opengl` thing is a build option, and usually only made use of in Windows, which has poor OpenGL support by default. On Linux OpenGL is usually always available if there's a graphics system installed. OP just misses the opengl development libraries, which actually should be dependencies of the Qt development package, i.e. should be automatically installed together with the Qt development package when installing using the package manager.
Comment: This is what I get when try to install OpenGL:  libgl1-mesa-dev : Depends: mesa-common-dev (= 8.0.4-0ubuntu0.6) or
                            mesa-common-dev-lts-quantal but it is not going to be installed or
                            mesa-common-dev-lts-raring but it is not installable
E: Unable to correct problems, you have held broken packages.
Comment: After that I install messa-common-dev and few other dependencies, but than my Ubuntu crashes and I cant start it again. I run it on VirtualBox...
Comment: @AleksaStancetic You can use Qt without opengl, but to install it(either by manually building or direct installer) you are going to need opengl. The exact reason of crash can vary a lot, you are also running it on VirtualBox, as you might know how VM works, it actually communicates to host OS to get actual service from h/w. Here is a quick link -- http://askubuntu.com/questions/162075/my-computer-boots-to-a-black-screen-what-options-do-i-have-to-fix-it which tries to cover how to solve your crash problem
Comment: @datenwolf If someone wants to go unusual way, it is possible. His question asks can he use Qt without opengl .. answer is yes! (though for installation it is needed). I think using opengl or not is completely dependent on what kind of application one is going to work on and not on windows/linux. Still I would like a link or something stating your usually's!
Comment: I don't use opengl in my projects so excluding it from build path would do the work, how can I do it? But after searching a little bit I think I have opengl installed, but it is not in usr/lib but in /usr/lib/i386-linux-gnu/mesa/ so maybe I need to change that path somewhere in Qt...

Using Qt without openGL


Where Did The "Resolve" Option Go In Visual Studio 2015?

Question: In previous versions of Visual Studio, I used to be able to right-click an unresolved class name, choose "Resolve" and then have the choice to add a using statement or fully-qualify the type.
However, that option appears to be missing for me since installing Visual Studio 2015. Anyone know where it went?
Answer: I figured it out.
It shows up as a little "Quick Actions" light bulb.
The "Resolve" wording is gone.
Comment: If using the mouse this is now a pain, in that you have to right-click to get the editor context menu, then select the "Quick Actions" option to get _that_ menu, then select the appropriate usings option. In other words, a right click followed by two other clicks (plus significant mouse movement), whereas before it was right-click and select one of the top two items from the menu. A step backwards in my opinion.
Comment: It adds the long name resolution, but is there a way to add a 'using' automatically any more?
Comment: The top option of the "Quick Actions" light bulb lets you choose "using Namespace.SubNamespace" to add it to the top of the file.
Comment: @StevenRands - I agree.
Comment: @StevenRands I also prefer the old menu system. CTRL+. and then enter supposedly has the same effect, which I'm sure I'll learn with time, but the fact that it's HIDDEN is bad :( It's also less reliable (for example, right now I'm not getting any quick actions to resolve anything from the System.Web namespace)
Answer: I had the same problem.
If you have dragged and dropped your work item to Done Column inside Web Portal of your TFS, then you can not check in your changes with Work Item set to resolve.
You have to first move back your work item to In Prgress column.


Synchronising Threads in CVI/Labwindows

Question: I have two (or more threads) working parallel. Their purpose is to measure hardware devices and they rely on a external hardware stimulus. At a certain point during execution, they trigger an hardware device and wait for the stimulus. But I have only one stimulus device.
Therefore the threads have to wait, till every thread is ready to receive the stimulus. Now another thread (maybe the dispatching main-thread) has to trigger the device and the threads can go on.
What is best practice to synchronise this? Preferable with a dynamic number threads?
EDIT:
We use CVI/Labwindows. That offers some threading but mostly through bad documented macros. I have figured out, how to register threads, start them and wait for them to finish.
There also seems to be tools to create threadsafe variables and locks. But their syntax eludes me, therefore I want/need to build some kind of mutex/semaphore myself.
Comment: If this is as you say, that it is badly documented perhaps change to a modern environment. It also seems based on C89, with some support for some C99 features. If you are just starting to use these tools, it is perhaps still time to change to a modern tool.
Comment: Avoid the CVI libs at all cost. They will make everybodys life miserable once you are able to switch.
Answer: I don't know if you mean that, the only version of C (ISO and ANSI) that has multi-threading is C11. There are not so much implementations for that around, so maybe you mean something different.
In C11, the tools to synchronize between threads are twofold. One are classical threading data structures, namely mutexes and conditional variables, in the same spirit that they are also present in POSIX threads. (semaphores only are an optional feature.)
The second tool for syncronizing threads in C11 are atomic variables. This is a feature that has no equivalent in POSIX, but is supported natively by all modern architectures.
Answer:
So first all your N worker-threads have to go into "ready mode"
Your stimulus thread sends the stimulus. (It has to wait until all the others are ready)
Then all the threads should start working.

So between 1. and 2. you need a semaphore (initial count 0, max count nThreads), which is signalled by each worker thread once, and waited for by the stimulus-thread N times.
Between 2. and 3. you also need a synchronisation, because the worker-threads should wait until the stimulus thread has sent his stimulus. This can also be achieved by a semaphore(initial count 0 max count 1) for each worker-thread.
pseudo-code for stimulus-thread:
init stimulus-semaphore and one semaphore for each worker-thread
start threads
while (1) {
  for (int i=0;i<nThreads;i++)
    wait for stimulus-semaphore
  do the stimulus-thing
  for (int i=0;i<nThreads;i++)
    signal threads[i] semaphore
}

pseudo code for worker-thread:
while (1) {
  signal stimulus-semaphore
  wait for this threads semaphore
  do the work to be done after stimulus was sent
}

Comment: Thanks, I guess, that will solve the thing. I don't need to wait for the stimulus, that is a active waiting for a hardware signale. The magic sentence was "counting semaphore" at main-thread with the pseudocode.

Synchronising Threads in CVI/Labwindows


Should I install a wall before or after hardwood floor installation?

Question:
Possible Duplicate:
Frame or floor planks first?

I am building a small wall between two rooms. The existing flooring was carpet, which I have removed. I plan to install a floating floor (the floor is concrete, on the 4th floor). My question is should I install the channel for the wall directly on the concrete and then build the wall and install the floor around it, or install the flooring first and then build the wall on top?
If it makes a difference, the wall will be small, only about 16"x5"x96"
Comment: @NiallC. I think my question is different, as I'm asking about a floating floor and not a traditional wood floor. Though it looks as though the answer is similar none-the-less.
Answer: If you are using a true floating floor like Pergo or a similar product I would suspect that the wall would need to be done first.If you build the wall on top of the flooring it will no longer float and buckling will occur as the flooring expands and contracts.This is why they recomend spacing between the flooring and fixed points like walls,cabinets etc.
Comment: This was my thought too, but I wanted to make sure.


PHP - Sort array data based on days and time

Question: I'm trying to create a table with data entries in a specific layout based on days and times.
For example we have store opening times:
Mon - Fri 0900 - 1200
Mon - Fri 1300 - 1700
The table should show:
Day  Open Closed Open Closed
Mon  0900 1200   1300 1700
Tue  0900 1200   1300 1700
Wed  0900 1200   1300 1700
Thur 0900 1200   1300 1700
Fri  0900 1200   1300 1700

If the opening times also include the following:
Wed - Wed 0900- 1100
Wed - Wed 1300- 1700
The table would show
 Day  Open Closed Open Closed
    Mon  0900 1200   1300 1700
    Tue  0900 1200   1300 1700
    Wed  0900 1100   1300 1700
    Thur 0900 1200   1300 1700
    Fri  0900 1200   1300 1700

And so on as other entries are added.
So far I've got the data coming in as an array as follows:
Array
(
    [0] => Array
        (
            [0] => 1
            [1] => 1
        )

    [1] => Array
        (
            [0] => 5
            [1] => 5
        )

    [2] => Array
        (
            [0] => 09 : 00
            [1] => 12 : 00
        )

    [3] => Array
        (
            [0] => 11 : 00
            [1] => 17 : 00
        )

)

Where:
[0] is the First Day (Monday = 1)
[1] is the Second Day (Friday = 5)
[2] is the opening time
[3] is the closing time

I'm looping through the array and creating new arrays based on Days, opening and closing times,
foreach ($array as $arr => $val) {
        if ($arr === 0) $start = $val;
        if ($arr === 1) $end = $val;
        if ($arr === 2) $open = $val;
        if ($arr === 3) $close = $val;
    }

But I can't see how to go from here to get the required output.
Can anyone point me in the right direction ?
Thanks
UPDATE
The following days and times,
Mon - Fri   09 : 00 17 : 00
Wed - Wed   13 : 00 17 : 00
Wed - Wed   09 : 00 12 : 00

Create this array
Array
(
    [0] => Array
        (
            [0] => 1
            [1] => 3
            [2] => 3
        )

    [1] => Array
        (
            [0] => 5
            [1] => 3
            [2] => 3
        )

    [2] => Array
        (
            [0] => 09 : 00
            [1] => 13 : 00
            [2] => 09 : 00
        )

    [3] => Array
        (
            [0] => 17 : 00
            [1] => 17 : 00
            [2] => 12 : 00
        )

)

UPDATE
The resulting output should look like this:
 Day  Open Closed Open Closed
    Mon  0900 1200   1300 1700
    Tue  0900 1200   1300 1700
    Wed  0900 1100   1300 1700
    Thur 0900 1200   1300 1700
    Fri  0900 1200   1300 1700

Further Example
PHP Array
array(4) { [0]=> array(5) { [0]=> int(1) [1]=> int(3) [2]=> int(3) [3]=> int(6) [4]=> int(0) } [1]=> array(5) { [0]=> int(5) [1]=> int(3) [2]=> int(3) [3]=> int(6) [4]=> int(0) } [2]=> array(5) { [0]=> string(7) "0900" [1]=> string(7) "1300" [2]=> string(7) "0900" [3]=> string(7) "0200" [4]=> string(7) "0900" } [3]=> array(5) { [0]=> string(7) "1700" [1]=> string(7) "1700" [2]=> string(7) "1200" [3]=> string(7) "2100" [4]=> string(7) "1300" } }

JSON
[[1,3,3,6,0],[5,3,3,6,0],["0900","1300","0900","0200","0900"],["1700","1700","1200","2100","1300"]]

Mon  0900   1700
Tue  0900   1700
Wed  0900   1200
Wed  1300   1700
Thur 0900   1700
Fri  0900   1700
Sat  0200   2100
Sun  0900   1300

Comment: so in the first half of the array there are the days that are referring to the second half? can you please post a real input/output example (so that i can use it to test a possible solution)?
Comment: @Berto99 - I've updated the question with data captured using var_dump. Thanks
Comment: sorry, that array is the input or output array?
Comment: @Berto99 that is the output I have to work with, its being passed by JS to PHP and then json decoded. The data that is passed is `[[1,3,3],[5,3,3],["09 : 00","13 : 00","09 : 00"],["17 : 00","17 : 00","12 : 00"]]`
Answer: This should work:
<?php
$arr = [[1,3,3],[5,3,3],["09 : 00","13 : 00","09 : 00"],["17 : 00","17 : 00","12 : 00"]];
$days = [
    1 => 'Mon',
    2 => 'Tue',
    3 => 'Wed',
    4 => 'Tur',
    5 => 'Fri',
    6 => 'Sat',
    7 => 'Sun',
];
for($i = 0 ; $i < sizeof($arr[0]) ; $i++){
    echo $days[$arr[0][$i]]." - ".$days[$arr[1][$i]]." : ".$arr[2][$i]." - ".$arr[3][$i]."\n";
    // shorter and cleaner way:
    // echo "{$days[$arr[0][$i]]} - {$days[$arr[1][$i]]} : {$arr[2][$i]} - {$arr[3][$i]} \n";
}

Output:
Mon - Fri : 09 : 00 - 17 : 00
Wed - Wed : 13 : 00 - 17 : 00
Wed - Wed : 09 : 00 - 12 : 00

Comment: Thanks this helps a lot. Its very nearly what I need.  Any way to expand the Mon-Fri so they are show as individual days ? and order Wed so 0900=1200 appears before 1300-1700 ?
Comment: @tom you mean that instead of  `Wed - Wed : 13 : 00 - 17 : 00
Wed - Wed : 09 : 00 - 12 : 00` you want `Wed - Wed : 09 : 00 - 12 : 00     13 : 00 - 17 : 00`
Comment: if that is the case @tom, it's not as easy as this version, but i can try
Comment: I've updated my ticket with the layout I'm trying to get. Thanks
Comment: @Tom please post coherent result, on your testing input there is no information about Saturday and Sunday, post the desired output for that input sample
Comment: Updated question with details.


Headless UI Menu component open by default

Question: i need to get this component opened by default without loosing the open closed default behavior.
What is interesting is that they to this in the example of the documentation, but when you copy paste the code under the "code" tab, it is closed by default.
https://headlessui.com/react/menu
Thanks
I managed to get the component opened by default by adding static as stated in the doc + adding show={true} on the transition component but with this solution, i cant close it.
I was expecting some prop like default={'open'} but i can't find it in the documentation
Answer: One option I found is to simulate click on a Menu Button following this answer
<Menu.Button ref={(e) => {e.click()}} onClick={() => console.log("Clicked")}>
    MyButton
</Menu.Button>

Looking for a better option though..
Answer: As @gman mentioned before, you should trigger click event by yourself but with more control of button template (because now all events and attributes will be on your wrapper):
(Note: I'm not a react developer but I tried it in vue and worked)

So, you should make your template to have no wrapper (your custom wrapper) with as={React.Fragment}

Note: You can make it work without as={React.Fragment} too but as I said before it is for more control over your button
<Menu.Button as={React.Fragment} ref="el">
   <button>More</button>
</Menu.Button>

Then in mount hook of your component you can trigger click event and that will open menu

// I don't know react hooks so it is sudo code
onMounted(() => {
   el.click() // el will be your 'button' tag you defined
})

I hope it helps.


Use Xdebug var_dump function without enabling other features

Question: I only use var_dump functionality from xdebug extension.
I have set php.ini to xdebug.mode = develop.
But develop mode slows the whole application (I am assuming it enables a lot more features other than just var_dump).
Is it possible to enable only var_dump feature and disable all the rest of the features from Xdebug extension?
Answer: No, that is not possible. However, you can set xdebug.mode=off and call it as xdebug_var_dump() instead.
Comment: `xdebug_var_dump` sounds perfect. Is it possible to override `var_dump` with `xdebug_var_dump` myself in `auto_prepend_file` maybe?
Comment: I don't think so!


Regex.Matches c# double quotes

Question: I got this code below that works for single quotes.
it finds all the words between the single quotes.
but how would I modify the regex to work with double quotes?
keywords is coming from a form post
so
keywords = 'peace "this world" would be "and then" some'

    // Match all quoted fields
    MatchCollection col = Regex.Matches(keywords, @"'(.*?)'");

    // Copy groups to a string[] array
    string[] fields = new string[col.Count];
    for (int i = 0; i < fields.Length; i++)
    {
        fields[i] = col[i].Groups[1].Value; // (Index 1 is the first group)
    }// Match all quoted fields
    MatchCollection col = Regex.Matches(keywords, @"'(.*?)'");

    // Copy groups to a string[] array
    string[] fields = new string[col.Count];
    for (int i = 0; i < fields.Length; i++)
    {
        fields[i] = col[i].Groups[1].Value; // (Index 1 is the first group)
    }

Comment: Wouldn't it work to put the quotes in the string? @-strings use "" instead of \" for quotes. `@"""(.*?)"""`
Answer: You would simply replace the ' with \" and remove the literal to reconstruct it properly.
MatchCollection col = Regex.Matches(keywords, "\\\"(.*?)\\\"");

Comment: No need to escape `"` in regex.
Comment: prefect. and if I wanted to include the quotes in the string?
Comment: @user713813: Move the brackets (as well as the _nongreedy_ mark) to the respective ends of the string.
Comment: According to https://regex101.com/ it's necessary to use `""` in C#/.NET (two consecutive double quotes) to match a single double quote. Unlike Python for instance where you'd simply escape the double quote with a backslash.
Comment: Thanks for that modernization update @domjancik. When this was answered back in 2012, the backslash escape character was the preferred method. I think at the time the double quote only worked in VB.Net, and I could be wrong about that.
Answer: The exact same, but with double quotes in place of single quotes. Double quotes aren't special in a regex pattern. But I usually add something to make sure I'm not spanning accross multiple quoted strings in a single match, and to accomodate double-double quote escapes:
string pattern = @"""([^""]|"""")*""";
// or (same thing):
string pattern = "\"(^\"|\"\")*\"";

Which translates to the literal string
"(^"|"")*"

Answer: Use this regex:
"(.*?)"

or
"([^"]*)"

In C#:
var pattern = "\"(.*?)\"";

or
var pattern = "\"([^\"]*)\"";

Answer: Do you want to match " or ' ?
in which case you might want to do something like this:
[Test]
public void Test()
{
    string input = "peace \"this world\" would be 'and then' some";
    MatchCollection matches = Regex.Matches(input, @"(?<=([\'\""])).*?(?=\1)");
    Assert.AreEqual("this world", matches[0].Value);
    Assert.AreEqual("and then", matches[1].Value);
}

Regex.Matches c# double quotes


Auto size windows

Question: Hey I used a gnome extension some time ago (unfortunately I forgot the name) which resized every open window when I opened a new one.
For example I only got a firefox window and started netbeans the screen splitted and the firefox window was on the one side and netbeans on the other (like flexbox in css). Is there an application on ubuntu 16.04 for that?
Comment: Off the top of my head, I don't know how you could automate resizing upon opening a new window, BUT there are a lot of really easy shortcuts that might be just as good (and possibly a better solution since you would maintain some control over what's happening). 1) You could use window snapping--for example, dragging an open window towards the far right side of your screen automatically resizes the window so it takes up the right half of the screen. You can define what part of the screen does what to the window, and there are lot of size options, like top half, bottom right corner, etc.
Comment: Just install the Unity Tweak tool to use window snapping. 2) There are built in keyboard shortcuts that can resize the active window to take up the left or right half of the screen. `Ctrl`+`Super`+`Left Arrow` and `Ctrl`+`Super`+`Right Arrow`. There are also shortcuts for keypads, but not everyone has those.
Comment: Also, [this answer](https://askubuntu.com/a/5026/787506) has a lot of suggestions that sound great (some I will even look into using myself!). For example, PyWO lets you tile windows using a keyboard shortcut. But again, none of them completely automate the process of window resizing--there's still some element of user input.
Comment: Finally, you may want to check out [i3](https://i3wm.org/screenshots/#)! I just found out about it and it sounds like it just might meet your needs. Here's a [comparison](https://www.slant.co/versus/1287/1290/~xmonad_vs_i3) to xmonad.
Comment: @Emily awesome thank you so much for your answers. i3 was the package I used back then (So it's the right answer for the question).
Comment: You're welcome, glad I could help! :) I wasn't sure if any of those options were a proper answer to your question but I will post as an answer now for anyone who has the same question in the future.
Answer: i3 is a well-documented tiling window manager that does what you are looking for.
"Tiling window managers [...] lay out their windows in logical subdivisions, breaking down the screen space in a logical pattern. For example, the first two windows that you open on your screen will each take up half of the screen and sit directly next to each other." (Source: Make Tech Easier)
In addition, there are a lot of really easy shortcuts that are good to know about, since you would maintain some control over what's happening:

There are built in keyboard shortcuts that can resize the active window to take up the left or right half of the screen. Ctrl+Super+Left Arrow and Ctrl+Super+Right Arrow. If you have a number pad, you can also use Ctrl+Alt+keypad number
You could use window snapping--for example, dragging an open window towards the far right side of your screen automatically resizes the window so it takes up the right half of the screen. You can define what part of the screen does what to the window, and there are lot of size options, like top half, bottom right corner, etc. Window snapping is a feature part of Unity Tweak Tool. To install, open Terminal/other CLI and enter:
sudo apt-get install unity-tweak-tool

Window Snapping is under the Window Manager category.

Finally, there's a lot of great suggestions in this answer. In particular, PyWO sounded interesting to me. For example, you can set it up so that you're able to move windows and snap them to windows' edges.

Auto size windows


laravel - unable to get data outside foreach

Question: dump($data) outside the foreach loop gives me only 1 data where as dump($data) inside the foreach shows all arrays of rows of data . How can i get all rows of data outside the foreach too?
        $skillId = $request->skillId;
        if (CourseFiles::where('skillId', $skillId)->exists()) {

            $courseId = CourseFiles::where('skillId', $skillId)->get(['courseId']);
            foreach ($courseId as $row) {

                $id = Course::find($row);
                $data = [];
                $data['courseDisplayName'] = $id[0]['courseDisplayName'];
                $data['courseInfo'] = $id[0]['courseUniqueName'];
                $data['paidStatus'] = $id[0]['paid_status'];
                $data['coursePatternsId'] = $id[0]['course_patterns_id'];

                $fileId = CourseFiles::where('skillId', $skillId)->get(['fileId']);
                $id = Uploads::find($fileId);

                $data['filePath'] = $id[0]['FilePath'];
                $contentTypeID = $id[0]['FileType'];

                $id = ContentTypes::find($contentTypeID);
                $data['file_height'] = $id[0]['height'];
                $data['file_width'] = $id[0]['width'];
                dump($data);
            }

//dump($data);

            if ($data) {
                return response()->json([
                    'message' => 'Fetched Data successfully',
                    'data' => $data,
                    'statusCode' => 200,
                    'status' => 'success'
                ], 200);
            }
  }

EDIT:
$response[]=$data;
$response->paginate(5);

Error: Call to a member function paginate() on array
Comment: need to push every array before next iteration in foreach
Comment: @RushikeshGanesh so, what line of code shall i give there? can u give me an example line of code?
Comment: just put $data =[] before the foreach it will work
Comment: @RushikeshGanesh `$response[]=$data;` - i've given like this & now it's working.But i need to do paging on the result.`$response->paginate(5)` shows the error `Error: Call to a member function paginate() on array ` .How can i do the pagination here?
Answer: In Controller add new function for it
$data = $this->paginate($myArray);

After that crate that function for pagination
public function paginate($items, $perPage = 5, $page = null, $options = [])
    {
        $page = $page ?: (Paginator::resolveCurrentPage() ?: 1);
        $items = $items instanceof Collection ? $items : Collection::make($items);
        return new LengthAwarePaginator($items->forPage($page, $perPage), $items->count(), $perPage, $page, $options);
    }

return that $data in response
Comment: for `Collection`, which class has to be imported?
Comment: use Illuminate\Support\Collection;


How to plot a background in a Pine Script indicator only the first time the condition is met?

Question: I've managed to create an indicator which measures the price change (%) of a selected asset from a user specified hour of the day every day. I've also included a background color change of the indicator whenever the price change reaches a user specified level (only positive numbers for now). However, I'd like to change the background color only the first time the specified price change level is reached in a day. What would you suggest?
Thank you.
<code>//@version=5
indicator(title = 'Price Change (%) From a Specific Time of the Day', shorttitle = 'PC (%)', overlay = false)

input_hour = input.int(title = 'Hour', minval = 0, maxval = 23, defval = 23, tooltip = 'Selected time is in the timezone of the exchange.')
input_minute = input.int(title = 'Minute', minval = 0, maxval = 59, defval = 0)
input_percentage = input.int(title = 'Price Change (%) Signal Level', minval = 0, maxval = 1000, defval = 5)

var initial_time = 0.0
initial_time := hour == input_hour and minute == input_minute ? close : initial_time
price_change_percentage = math.round((close - initial_time) / initial_time * 100 * 100) / 100
price_change_percentage_crossover = ta.crossover(price_change_percentage, input_percentage)

price_change_line_color = price_change_percentage > 0 ? color.new(#089981, 0) : price_change_percentage < 0 ? color.new(#f23645, 0) : na
plot(price_change_percentage, title = 'Price Change (%) Color', color = price_change_line_color, linewidth = 1)
hline(price = 0, title = 'Zero Line', color = color.new(color.white, 70))
bgcolor(hour == input_hour and minute == input_minute ? color.new(color.white, 80) : na, title = "Selected Time Background")
bgcolor(price_change_percentage_crossover == true ? color.new(color.green, 50) : na, title = "Price Change Cross Background")
</code>
Answer: I achieved what you are asking by creating a boolean that turns true once the price change crossover has occurred and then resets every new day.
<code>//@version=5
indicator(title = 'Price Change (%) From a Specific Time of the Day', shorttitle = 'PC (%)', overlay = false)

input_hour = input.int(title = 'Hour', minval = 0, maxval = 23, defval = 23, tooltip = 'Selected time is in the timezone of the exchange.')
input_minute = input.int(title = 'Minute', minval = 0, maxval = 59, defval = 0)
input_percentage = input.int(title = 'Price Change (%) Signal Level', minval = 0, maxval = 1000, defval = 5)

var priceChangeReached = false
var initial_time = 0.0

newDay = ta.change(time('D'))
initial_time := hour == input_hour and minute == input_minute ? close : initial_time
price_change_percentage = math.round((close - initial_time) / initial_time * 100 * 100) / 100
price_change_percentage_crossover = ta.crossover(price_change_percentage, input_percentage)

if price_change_percentage_crossover
    priceChangeReached := true

price_change_line_color = price_change_percentage > 0 ? color.new(#089981, 0) : price_change_percentage < 0 ? color.new(#f23645, 0) : na
plot(price_change_percentage, title = 'Price Change (%) Color', color = price_change_line_color, linewidth = 1)
hline(price = 0, title = 'Zero Line', color = color.new(color.white, 70))
bgcolor(hour == input_hour and minute == input_minute ? color.new(color.white, 80) : na, title = "Selected Time Background")
bgcolor(price_change_percentage_crossover and priceChangeReached[1] == false ?  color.new(color.green, 50) : na, title = "Price Change Cross Background")

if newDay
    priceChangeReached := false
</code>


Understanding CORS on UPnP/DLNA browsing

Question: I've been playing around with home-grown UPNP/DLNA Browsing.
What I manage to do is a shell script based approach using curl to query the Server and xsl processing to make html pages out of the answers.
Next I thought I could build all this into javascript/kind of interactive browser page. But now I hit the CORS issue as the requests are preflighted by the browser (they are not preflighted when using curl and the server speaks no CORS, just UPnP).
Some simplest code trying to get the root of the upnp tree:...

Clearly the browser (Firefox 47.0) hits
Cross-Origin Request Blocked: The Same Origin Policy disallows reading
the remote resource at http://hcds6106:50001/ContentDirectory/control.
 (Reason: CORS header 'Access-Control-Allow-Origin' missing).

Is there any reasonable way I can tell my browser to skip the CORS stuff in this case because the server was not made for it? For Firefox or any other common UserAgent? I can't believe it can be so simple without a browser and close to impossible to get it interactive inside browser.... TIA!
Comment: no means no, but there are plenty of workarounds; proxy with php, build an app with nw.js, use an extension, disable security on the browser with a command-line argument, etc. I keep a portable copy of chrome for such uses.
Comment: Okay, thanks, looks like the [CorsEverywhere](https://addons.mozilla.org/en-US/firefox/addon/cors-everywhere/?src=search) firefox addon can do this job
Answer:
Is there any reasonable way I can tell my browser to skip the CORS stuff in this case because the server was not made for it?

No.
If it was possible, then I could tell the browsers of visitors to my website to skip the CORS stuff and let me read their data from their online banking and webmail services as well as their company intranet.
Comment: Thx, but how about if it was the visitors' decision? And not yours to disable cors from the server?
Comment: I understand. Nothing else left but to use [CorsEverywhere](https://addons.mozilla.org/en-US/firefox/addon/cors-everywhere/?src=search) to tweak my browser into believing that the server would accept my cross origin calls...


Pagesetup.printquality Causing type mismatch error

Question: I recorded a macro for page setup and it generated a whole wack of properties that get set.  I then ran said macro, got caught up on some correspondences, went to the washroom, grabbed a coffee, and sat back down and waited for the pagesetup macro to finish.  Needless to say it is incredibly slow to process.
I did some google searching and discovered its a notoriously slow thing to run and came across three suggestions.

use Built in VBA 4 Macro for doing most of your pagesetup properties as it runs faster.
limit the properties you are changing
only change the properties that need changing

3 is kind of similar to 2 and it was the route I decided to take.  Basically I would run each property change through an if statement.
IF .property <> wanted.value then .property = wanted.value

So through a bit of text manipulation I quickly converted the recorded macro where it set all the property values to an IF THEN check before setting corresponding values.
When I ran the code I got an error  "Type Mismatch".  It did not take me to any particular line.  However when I stepped through the code, it crashed at the following line:
If .PrintQuality <> 600 Then .PrintQuality = 600

The line with out the IF works fine without error
.PrintQuality = 600

The IF THEN coding worked on several lines proceeding this one.  What is wrong with the PRINTQUALITY check that is throwing the error?
SAMPLE CODE
Sub SetupPage(ByVal wks As Worksheet)

Select Case wks.Name
    Case Worksheets(2).Name
        'Set Page size margins etc
        With wks.PageSetup
            If .PrintTitleRows <> "$1:$12" Then .PrintTitleRows = "$1:$12"
            If .PrintTitleColumns <> "" Then .PrintTitleColumns = ""
            If .LeftHeader <> "" Then .LeftHeader = ""
            If .CenterHeader <> "" Then .CenterHeader = ""
            If .RightHeader <> "" Then .RightHeader = ""
            If .LeftFooter <> "" Then .LeftFooter = ""
            If .CenterFooter <> "Page &P of &N" Then .CenterFooter = "Page &P of &N"
            If .RightFooter <> "" Then .RightFooter = ""
            If .LeftMargin <> Application.InchesToPoints(0.236220472440945) Then .LeftMargin = Application.InchesToPoints(0.236220472440945)
            If .RightMargin <> Application.InchesToPoints(0.236220472440945) Then .RightMargin = Application.InchesToPoints(0.236220472440945)
            If .TopMargin <> Application.InchesToPoints(0.748031496062992) Then .TopMargin = Application.InchesToPoints(0.748031496062992)
            If .BottomMargin <> Application.InchesToPoints(0.748031496062992) Then .BottomMargin = Application.InchesToPoints(0.748031496062992)
            If .HeaderMargin <> Application.InchesToPoints(0.31496062992126) Then .HeaderMargin = Application.InchesToPoints(0.31496062992126)
            If .FooterMargin <> Application.InchesToPoints(0.31496062992126) Then .FooterMargin = Application.InchesToPoints(0.31496062992126)
            If .PrintHeadings <> False Then .PrintHeadings = False
            If .PrintGridlines <> False Then .PrintGridlines = False
            If .PrintComments <> xlPrintNoComments Then .PrintComments = xlPrintNoComments

****************************************************************************
            If .PrintQuality <> 600 Then .PrintQuality = 600
****************************************************************************

            If .CenterHorizontally <> False Then .CenterHorizontally = False
            If .CenterVertically <> False Then .CenterVertically = False
            If .Orientation <> xlLandscape Then .Orientation = xlLandscape
            If .Draft <> False Then .Draft = False
            If .PaperSize <> xlPaperLetter Then .PaperSize = xlPaperLetter
            If .FirstPageNumber <> xlAutomatic Then .FirstPageNumber = xlAutomatic
            If .Order <> xlDownThenOver Then .Order = xlDownThenOver
            If .BlackAndWhite <> False Then .BlackAndWhite = False
            If .Zoom <> False Then .Zoom = False
            'set number of pages wide to 1 and length to as required
            If .FitToPagesWide <> 1 Then .FitToPagesWide = 1
            If .FitToPagesTall <> False Then .FitToPagesTall = False
            If .PrintErrors <> xlPrintErrorsDisplayed Then .PrintErrors = xlPrintErrorsDisplayed
            If .OddAndEvenPagesHeaderFooter <> False Then .OddAndEvenPagesHeaderFooter = False
            If .DifferentFirstPageHeaderFooter <> False Then .DifferentFirstPageHeaderFooter = False
            If .ScaleWithDocHeaderFooter <> True Then .ScaleWithDocHeaderFooter = True
            If .AlignMarginsHeaderFooter <> False Then .AlignMarginsHeaderFooter = False
            If .EvenPage.LeftHeader.Text <> "" Then .EvenPage.LeftHeader.Text = ""
            If .EvenPage.CenterHeader.Text <> "" Then .EvenPage.CenterHeader.Text = ""
            If .EvenPage.RightHeader.Text <> "" Then .EvenPage.RightHeader.Text = ""
            If .EvenPage.LeftFooter.Text <> "" Then .EvenPage.LeftFooter.Text = ""
            If .EvenPage.CenterFooter.Text <> "" Then .EvenPage.CenterFooter.Text = ""
            If .EvenPage.RightFooter.Text <> "" Then .EvenPage.RightFooter.Text = ""
            If .FirstPage.LeftHeader.Text <> "" Then .FirstPage.LeftHeader.Text = ""
            If .FirstPage.CenterHeader.Text <> "" Then .FirstPage.CenterHeader.Text = ""
            If .FirstPage.RightHeader.Text <> "" Then .FirstPage.RightHeader.Text = ""
            If .FirstPage.LeftFooter.Text <> "" Then .FirstPage.LeftFooter.Text = ""
            If .FirstPage.CenterFooter.Text <> "" Then .FirstPage.CenterFooter.Text = ""
            If .FirstPage.RightFooter.Text <> "" Then .FirstPage.RightFooter.Text = ""
        End With

    Case "FOO"
        With wks.PageSetup
            'Set all the stuff above to some other values
        End With

    Case Else
        With wks.PageSetup
            'Set all the stuff above to some other values
        End With
    End Select
End Sub

Comment: Maybe enclose within `On Error Resume Next... On Error GoTo 0`. Not sure, I can't test it.
Comment: See the [docs](https://learn.microsoft.com/en-us/office/vba/api/excel.pagesetup.printquality) though it seems like the answer may be dependent on your printer driver (?, untested).
Comment: @BigBen I saw that in the docs, but shouldn't also throw the error when setting it?
Comment: Is it possible it is an array initially? Check with `TypeName` perhaps?
Comment: @BigBen I was just looking at that, and yes it is a default 1 to 2 array.  I added `wks.pagesetup.printquality` to the watch window.  If I change it to `.printquality(1)` it seems to run fine.  According to the doc it sounds like .printquality(2) is not always supported.  How would you deal with a line of could that may or may not work since it based on printer driver?
Comment: So the `.PrintQuality <> 600` will throw a type mismatch then, yeah what I expected.
Comment: @ForwardEd Pagesetup is slow because everytime you change a parameter the document has to be reformatted even though your change may only affect one page.  So for your first attempts at speeding up a macro make sure that you set screenupdating = False at the start of your macro and then set it to true at the end of your macro
Comment: @Freeflow Was that comment supposed to be on my other question by chance?  I will try adding in the screen updating toggle to the print sub.
Answer: From the PageSetup.PrintQuality documentation,

Horizontal print quality (1) or vertical print quality (2). Some printers may not support vertical print quality. If you don't specify this argument, the PrintQuality property returns (or can be set to) a two-element array that contains both horizontal and vertical print quality.

So .PrintQuality <> 600 returns a Type Mismatch due to comparison of 600 to an array.
Since the docs mention that trying to set the vertical print quality may fail if not supported by the printer, I suppose something like this may be the answer (but untested, as my printer supports both):
On Error Resume Next
If .PrintQuality(1) <> 600 Then .PrintQuality(1) = 600
If .PrintQuality(2) <> 600 Then .PrintQuality(2) = 600
On Error GoTo 0


Explode matching columns

Question: I'm using spark to read a csv that contains 2 columns that are arrays, where each cell in the first array matches a cell in the 2nd array, that is:
arr1[i] <-> arr2[i]

The reading:
val table = spark.read.csv("my_data.csv")

Example of the data:
+---------+---------------------+
| ids     |  avg                |
+---------+---------------------+
|  [11,23]|  [0.368633,0.750615]|

I would like to explode the columns in a corresponding matter such that for each row, 'id' and 'avg', will match (and not getting all combinations).
Answer: try posexplode it creates 2 columns one for array values and another for indexes
      //first explode and rename position columns
table.select(posexplode($"ids") as Seq("id_pos", "id"), $"avg").
     .select($"id", $"id_pos", posexplode($"avg") as Seq("avg_pos", "avg"))
      //then keep only rows with the same array position
     .filter($"id_pos" === $"avg_pos")
      //remove positions from dataframe
     .select($"id", $"avg")

Comment: There's a small mistake here - `posexplode` creates two columns where the _first_ is the position, so the naming of the result columns is wrong (which makes the results wrong): should be `as Seq("id_pos", "id")` and `as Seq("avg_pos", "avg")`.
Comment: @TzachZohar Thank you! fixed
Answer: You could use a small udf:
val df = spark.createDataFrame(
    Seq((
      Array(11, 23),
      Array(0.368633, 0.750615)
    ))).toDF("ids", "avg")

val udfZip = udf((ids: Seq[Int], avg: Seq[Double]) => ids.zip(avg))

val res = df.select(explode(udfZip($"ids", $"avg")).as("pair"))
res.show
// +-------------+
// |        pair|
// +-------------+
// |[11,0.368633]|
// |[23,0.750615]|
// +-------------+

res.printSchema
// root
//  |-- pair: struct (nullable = true)
//  |    |-- _1: integer (nullable = false)
//  |    |-- _2: double (nullable = false)

Or even better UDF:
case class Pair(id: Int, avg: Double)
def udfBetterZip = udf[Seq[Pair], Seq[Int], Seq[Double]](
    (ids: Seq[Int], avg: Seq[Double]) =>
        ids.zip(avg).map{
            case (id, avg) => Pair(id, avg)
        }
)

val res2 = df.select(explode(udfBetterZip($"ids", $"avg")).as("pair"))
res2.printSchema
// |-- pair: struct (nullable = true)
// |    |-- id: integer (nullable = false)
// |    |-- avg: double (nullable = false)

Comment: This relies on being able to specify the types for each sub-array, which isn't practical when they are arrays of StructType.

Explode matching columns


Files Drag and drop using jquery

Question: I am creating a website in php. Client demanded for drag and drop feature in image gallery so that
  he can just drag and drop images in gallery from anywhere.
Please suggest me some good site or code ?
Answer: That is a feature of the browser, and your client can only use browsers that have this method implemented, such as Google Chrome and Firefox
It's called the File-API in HTML5
Remmy Sharp as a nice example on it

Files Drag and drop using jquery


Which fuels burn the longest in Minecraft?

Question: What's the order of "best fuels"?
Example: Coal cooks less than lava and blaze rods, wood cooks less than coal, etc.
What's the order of fuels based on their 'cooking quantity'?
Comment: Just use stacks of coal, they work the best and you can smelt 8 items with one coal so a total of 512 items with one stack of coal.
Answer: Fuel efficiency found in Smelting
<code>                           Burn Time  Burn Time     Fuel needed to
Fuel                        (ticks)   (smeltings*)  smelt 64 items
----------------------------------------------------------------------
Lava Bucket                  20000         100                0.64
Block of Coal                16000          80                0.8
Blaze Rod                     2400          12                5.3
Coal and Charcoal             1600           8                8
Huge Mushrooms                 300           1.5             43
Wood and wooden things†        300           1.5             43
Daylight Sensors               300           1.5             43
Banners                        300           1.5             43
Wood tools and weapons         200           1               64
Wooden Slabs                   150           0.75            86
Stick                          100           0.5            128
Saplings                       100           0.5            128

* Number of items smelted per fuel item
† Anything mostly crafted from wood: Crafting tables, Chests, Jukebox (Except Slabs)
</code>
Note that the effective efficiency of the long-burning materials goes down rapidly if you don't restock the furnace.
Comment: Do note that efficiency is not the only thing you should take into account. Renewability (is a resource infinite or not) comes into play too, as well as "obtainability" (how easy is it to get/transport the resource). Lava buckets use iron, which is non-renewable. Blaze rods are infinite, and easily obtainable when you have a blaze spawner.
Comment: @Konerak The bucket is not used up during the smelting process, so the renewability of the 3 iron bars used to make it is of minimal concern for large smelting operations - in reality you're much more likely to run out of lava.
Comment: @Konerak Iron _is_ renewable, through the use of iron golem farms. However these are impractical to make and are usually mistaken for being unrenewable.
Comment: Would be awesome if charcoal blocks existed
Comment: So, at the risk of stating the obvious: combine your coal into blocks (if you're smelting large quantities that is) and split your wood into sticks before burning it - or better yet convert it to charcoal first.
Comment: @Psychemaster: Once I get to the Nether, though, or find some underground lava lakes, lava immediately becomes my prime fuel source. The thing about lava is, besides small single-source-block streams you find in cave tunnels, it _always_ comes in huge quantities.
Answer: Sorting the entries in this table based on the last column gives this list:

Lava Bucket
Block of Coal
Blaze Rod
Charcoal
Coal
Fence
Fence Gate
Wooden Stairs
Wooden Pressure Plate
Wood Planks
Wood
Chest
Trapped Chest
Daylight Sensor
Bookshelf
Crafting Table
Trapdoor
Huge Mushrooms
Note Block
Jukebox
Wooden Tools and Weapons
Wooden Slabs
Stick
Saplings
Answer: Found an even better list
Under the section "Fuel efficiency"
From most to least efficient (according to new list):

Lava Bucket
Block of coal
Blaze rod
coal
charcoal
Huge Mushrooms
Note Block
Jukebox
Daylight Sensor
Trapped Chest
Chest
Bookshelf
Crafting table
Trapdoor
Wooden Stairs
Fence Gate
Fence
Wooden preasure plate
Wood
Wood Planks
Wooden Tools and Weapons
Wooden slabs
Stick
Saplings

@Meraj99 - Because you can use them as fuel for a furnace xD
Comment: Burning jukeboxes...it's like a _really efficient_ CD burning. Cast out the devil's music and repent!
Comment: Why are there bookshelves, huge mushroom blocks, swords in the list....
Answer: 1. Lava Bucket.
2. Block of Coal
3. Blaze Rod.
4. Coal and Charcoal.
Since Block of Coal is stackable, that makes it a little better than Lava Bucket, because as Celta's answer states that Lava Bucket can cook 100 meat, Block of Coal doing 80. A stack of Block of Coal would be 80x64, doing simple math would tell you that (80x64) is bigger than 100. I hope this helped. (Please don't remove hashtags)
Answer: Lava bucket, block of coal, blaze rods, coal and charcoal are the good fuels, however if you are in a survival situation, you may need to use items like saplings and sticks.
Answer:
bucket of lava
coal block
blaze rod
coal/charcoal
jukebox
note block
wood
sticks
saplings
Comment: ....don't you mean _coal_ block?
Answer: Greatest to least: Blaze Rod, Lava Bucket, Coal, Charcoal, Wood, Wooden Planks, Wooden Slabs, Wooden Tools, Saplings.
Comment: Um, that's greatest to least, and the order is kinda wrong.


How to hack a turret in Bioshock?

Question: I've found that most cameras can be hacked by sneaking another them and hacking from below. Also the flying helicopters can be hacked if they are protecting an enemy which is killed.
What I can't work out is how to directly hack a turret. It's difficult to get close to them without suffering severe health loss.
Is there any way to do this?
Answer: Use the Electro Bolt plasmid on them; this will shut the turret temporarily for enough time to get close enough.
Comment: Looks like [Winter Blast](http://bioshock.wikia.com/wiki/Winter_Blast) is similarly effective.
Comment: This also works on security bots that are attacking you.
Comment: Winter blast will also decrease the speed of the fluid.

How to hack a turret in Bioshock?


ec2 instance running continually

Question: just wondering is it possible that I can run an instance after I disconnect it?
The only thing I found is the link but it is not relevant to what I want.
link1
link2
Answer: I guess you mean keep it running in background?try
<code>sudo apt-get install screen
</code>
Comment: mank thanks, this one works

ec2 instance running continually


Proper size of header to support new door in load bearing wall?

Question: We're going to install a new linen closet off the hallway next to our recently(ish) remodeled bathroom.  The wall in question is load bearing.
I know how to properly build out the King and Jack studs, and if this weren't load bearing I'd just put in cripple studs, but since this is load bearing I figure on installing sistered 2x? over the doorway resting on doubled up jack studs.  The only question I have is - 2 by WHAT?
It's a 30" door if I recall correctly (it's reclaimed from another part of the house and I haven't measured it lately) so I'm thinking sistered 2x12's will be MORE than sufficient.
Comment: How many floors above this one?
Answer:
International Residential Code 2012
Chapter 6 Wall Construction
Section R602 Wood Wall Framing
R602.7 Headers. For header spans see Tables R502.5(1) and R502.5(2).

So if you're on the top floor, you can use 2 2x4's (unless the building is 36' wide, in which case you'll need 2 2x6's). If you have a floor above, you'll need 2 2x6's (unless the building is 36' wide, in which case you'll need 2 2x8's).
Comment: Just the attic above, so perfect.  I'll use x6 anyway just for overkill though.
Answer: Older buildings are 2X4 up and downstairs. Codes have changed, so remodeling will be a hassle if the permit inspectors don't know the history. Remodeling a 1950's house in ca, the planning guy was really helpful and gave me the strength for an open attic! I was told it was The actual strength or the amount of "wood".  AKA: 2 x 4 is 1 1/2 x 3 1/2 = 5.25 sq in. A 2X6 = 8.25si  So you'd need 2 2x4's to replace a 2x6. A simple call to a decent Planning Dept would answer that question. 1) Over-building always gives you a good impression with the inspectors. 2) Asking the Inspector first gives them the added impression you're trying to do things right!


Trying to figure out why my Rails alerts aren't working properly

Question: I cannot find an officially documented list of alert types in Rails, for whatever reason. In my controllers, I am redirecting users back, and so far, the redirect_back helper doesn't seem to be adding my second parameter to the flash variable.
For example, this works:
redirect_back fallback_location: users_path, notice: "Added user."

and this does not:
redirect_back fallback_location: users_path, danger: "Deleted user."

Here's what my views/layouts/application.html.erb looks like when it comes to displaying alerts:
  <% flash.each do |key, value| %>

  <div class="alert alert-<%= key_type(key) %> fade in">
    <button class="close" data-dismiss="alert">
      ×
    </button>
    <i class="fa-fw fa fa-<%= key_icon(key) %>">
    <%= key.capitalize %>: <%= value %>

  <% end %>

The reason I have a key_type and key_icon helper is because Rails seems to use these alert types, like notice, that doesn't fit with my theme's alerts.
So I placed a binding.pry right after the opening of flash.each, and I can see that if I redirect_back with notice set, it hits, meaning there's something in flash. But I've tried redirecting back with danger, error, warning, etc. and none of them work.
I'm not sure what I'm doing wrong, but I cannot figure out what actually gets set in flash.
If I set it manually before the redirect_back method, then it works flawlessly, like this:
flash[:danger] = "Deleted user."

but not with the redirect_back method.
Any suggestions?
Comment: Try with `redirect_back fallback_location: users_path, flash: { danger: 'Deleted user.' }`, what do you get?
Comment: @SebastianPalma hey there! this actually works. thanks man!
Answer: Check the official guides https://guides.rubyonrails.org/action_controller_overview.html#the-flash
By default it handles only notice and alert and you can use anything you want with the key flash. The example uses redirect_to but I guess redirect_back uses the same logic for flashes.