Python - very confused about method and while loop

Question: I have this method:
def is_active(self):
    if self.is_current_node():
        return True
    cur_children = self.get_children()
    while cur_children is not None:
        for child in cur_children:
            if child.is_current_node():
                return True
            raise Exception(child.display_name)
        cur_children = cur_children.get_children()
    return False

I put this method together and I put the raise Exception(child.display_name) to test out and "alert()" me to which child was being hit. The exception is never raised. You'd think that was because the function returned True on the if child.is_current_node() part. Well, if I replace the if part with this:
        for child in cur_children:
            if child.is_current_node():
                raise Exception(child.display_name)

It doesn't raise the exception still. If I do this however:
        for child in cur_children:
            raise Exception(child.display_name)

The exception is raised. I'm so confused. I'm sure this is something ridiculous but I was up till 2 and I can't think straight enough to wrap my tiny brain around this.
Comment: what's in the `is_current_node` method?
Comment: It just checks a static value against `self._url` and returns the comparison as a Boolean.
Comment: @Eric - shouldn't the exception be raised always in one of the first two versions? The second one says, `if True: raise` and don't return from the function. The first one says `raise` if none of the `if True:` return from the function.
Comment: @aaronasterling - If that's the case, why wouldn't the first version always raise the exception? The first one essentially says, "For each: if True: return; raise;"
Answer: If the first child in the list .is_current_node(), then the exception will never be raised in your first snippet.
Everything you have for evidence is supporting the idea that either self.is_current_node() is always true, or the first scanned child .is_current_node(). Given the third code snippet, the latter seems to be the case.
EDIT: removing a misunderstanding (child != self) :/
Actually, I have to ask, what is this supposed to do? It looks vaguely like recursive tree-traversal, but it's not quite there. (the cur_children = cur_children.get_children() line in particular is a bit strange)
Answer: Some ideas:
cur_children = self._children
    while cur_children is not None:
        for child in cur_children:
            if child.is_current_node():
                return True
            raise Exception(child.display_name)
        cur_children = cur_children._children
I assume that self._children contains multiple children: [A, B, C]
Then, on the first loop, it will take A. Let's assume that A has these children: [AA, AB, AC].
Now, you do this: cur_children = cur_children._children. This means that now, instead of continuing with B from the inital [A, B, C], it will continue with AA, and so on.
In this example, it will never reach B. Is this intended?

What does your is_current_node() contains? Probably you forgot to return a value, so the result is always None, and bool(None) == False.

Another idea: (recursion)
def is_active(self):

    def check_children(children):
        for child in children:
            if child.is_current_node():
                return True
            else:
                if children._children:
                    return check_children(children._children)
        return False

    if self.is_current_node():
        return True
    return check_children(children)

Comment: Thanks, but where is `children` defined or passed into the function in your example? Did you mean: `return check_children(self.children)`, or am I missing something? For some reason tree traversal is so confusing to me.
Answer: Maybe is_current_node always returns True and is_current_tab always returns False? I think more context is needed to give you an answer.
The only thing I can think of is that is_current_node changes state.
Comment: Ooops, see my edit. I changed the names while I was editing. Sorry, they're both the same function.


What are the pros and cons of adding a vapor barrier behind shower backer board?

Question: After much research, I have a lot of conflicting advise about the need to add a vapor barrier before installing the backer (hardy / cement) board for my bathroom shower.
The "expert" at Home Depot, and another guy on youtube seem to think this is a very good idea, and even suggest sealing it with roofing tape.  (The guy on Youtube tapes it directly to the sill of tub.)
However, when I asked about the tape and how far down I should go at Lowes, they told me they'd never hear of anyone doing that, and that it didn't seem like a good idea.   Likewise, Ask This Old House only recommends putting down caulking on the sill before applying the backer board, and then again after before adding tile, and then caulking a 3rd time under the tiles before grouting.
Should I add a vapor barrier between the frame and the cement board?  Why or why not?
Answer: You should NOT place a vapor barrier BEHIND the backer board.
Where, pray tell, would any such collected vapor/water go?
Answer:There's nowhere proper for such moisture to egress.
The current best practice is to place waterproofing OVER the backetboard and just UNDER the tile.  Thin sheet membranes like Kerdi or NobleFlex are examples
. Paint on membranes can also be used, such as RedGuard or AquaDefense.
This a is a recent job I completed illustrating Kerdi over Hardibacker.
Comment: While I agree the waterproofing should be on the inside as much as possible (I've used Redgard and like it) the use of plastic sheeting behind the cement board has been common practice (at least in the US) for a long time and may even be code in places (if you're not using the alternatives you've listed)
Comment: @virtualxtc it depends on the system you are installing, but most modern tubs have a lip that the plastic and cement board would overlap. Whether or not to caulk that spot is debatable. Some say that you want any water behind to eventually drain. Other's say that water should never get there to begin with and the plastic is just a last line of defense. (FWIW, I push Redgard as a better alternative, as the waterproofing is now closer to the water)
Comment: Vapor != moisture.  Is hardibacker a vapor barrier?  I bet it isn't.  Is kerdi or a paint on rubber barrier?  Probably.  What about the ceiling or the part of the wall without backer board-kerdi?  Do you need a vapor barrier?  What does your local code say?  What about your local climate?  Needs in Colorado are different than in Manitoba.
Comment: If he uses a product like durock, he *must* apply a barrier to protect the studs. This could be something like kerdi (in your example) or redgard or a traditional barrier but never more than one of these.
Comment: Do I put a plastic sheet up so local inspector doesn't throw a fit?  Yes.  Is it totally useless with HB?  Yes.  HB is basically waterproof.  I have let these boards sit in water for months with no affect so why do I need a sheet behind it?  (Little secret of mine... I might accidentally puncture said plastic in several places while installing HB on top) - The whole point is where is the water coming from that the plastic would help?  I am more worried about the wall on the other side of plastic sheet - if water is trapped in plastic sheet for a long time, mold could grow on nearby walls.
Comment: @DA01 is it also standard practice to leave gaps in the caulking to let the water drain from?
Comment: @DMoore not all backer boards are the same and they're not all rated to be moisture barriers. Whether one should have a separate moisture barrier is highly debatable, of course, and is why I tend to vote for the 'inside' method ala Redgard to get around the whole debate.
Comment: @DA01 - I use Redguard almost all the time now and I only use HB because it doesn't hold water.  If I used durarock or whatever other brand I would change my answer.  But still the whole thing about the moisture barrier... if water is getting there then that is probably the least of your problems.
Answer: I called USG,the maker of Durock cement board Next Gen, and they advised using no vapor barrier so that the wall cavity can breath and allow any moisture to evaporate. Their online instructions/diagrams show no use of a vapor barrier.
Answer: You should, so that any moisture that gets behind the cement board runs into the tub or shower instead of into your wall cavity (causing rot or mold/mildew).
If you overlap the moisture barrier with the raised lip around the tub, any moisture has only one path to take due to gravity -- down the barrier and into the tub.  I usually use thick-mil plastic sheeting, overlapped in shiplap fashion (overlapping, laid down from bottom to top -- like shingles).
Do caulk between the tub and tile, but leave small gaps for any water runoff down the sheeting to escape. I always take a level to the tub base to see where the water would run to if it had the chance, and place my holes appropriately.
You'll staple the sheeting to the framing -- don't worry about these minor penetrations of the barrier.
Comment: @Ethereal: Your comment about leaving 1cm gaps is relevant to me. I built a shower last year and wondered how any water coming down the vapor barrier would get into the shower base because I caulked the gap where the vapor barrier lipped over the shower base's outside edge. Having read your comment I'm now wondering whether I should drill some small weep holes through the caulk. Would you?
Comment: When you caulk around the tub, you need to leave small 1cm gaps every so often in the caulk for water to escape.
Comment: I'm confused about the shiplap, can one can buy rabbited thick-mil plastic sheeting? and I assume you mean horizontal not vertical shiplap such that the water will run down, correct? If I caulk the tub, wouldn't that just make it puddle behind the cement board?   What tape should I use? water-tight aluminum? tyvek tape?
Comment: The shiplap reference simply refers to the upper layer covering the edge of the lower layer, like roof shingles. Gravity does the water proofing. Although I am not an advocate of solid impermeable membranes, the small area behind the tile, should not create any mildew problems with the blockage of moisture that will need to pass through the walls. I just renovated my 1989 hall bath shower, tile over Wonderboard. When I pulled it down to the studs. there was no evidence at all of any water passing through the 4X4 tile. except in one corner where I never nailed the corner tight. I fixed that.
Comment: Ask TOH is usually right on, but how old was the segment? A vapor barrier behind the hardi-backer or concrete board is SOP today. These walls are also insulated for sound proofing so even more important to water seal the outer layer from the inner cavity.  If the plastic (6 mil min) is not large enough to cover the entire envelope in one piece, it should be installed at the bottom first, overlapped so water runs over the lap downhill, and taped at all joints.
Comment: @Ethereal you should add the bit about 1cm gaps to your answer, and preferably find a more accurate adjective than shiplap so we can vote your answer up!  :-)
Comment: @shirlockhomes it seems possible that gaps may wick water up behind the backer board via capillary action; how do I avoid this?  How can I ensure that all the gaps happen at the low points of the caulking seal (especially since it's smooshed in there) so that all puddling actually drains?
Comment: @shirlockhomes it's actually going up against an exterior brick wall.  The original contractor only had a radiant barrier, which clearly wasn't enough to keep the caulking from cracking almost monthly while I had a 3-piece tub-wall in there.  The framing is only 3/4" deep, so I've added styrofoam sheets.
Comment: @shirlockhomes the Ask TOH advice happens at 14:34 in the video lined above, dated October 19, 2006Season 5: Ep. 3
Comment: @getterdun I would, and the holes don't need to be very big to do their job -- you really just want somewhere for evaporated water to go.
Comment: @virtualxtc -- I'll try to find a more common adjective, but nothing is coming to mind atm! Edit -- I couldn't find one, but added a description instead.
Answer: plastic behind cement board with waterproofing is essentially suspenders when you already have a belt.  the waterproofing is also a vapor retarder so if the red guard or kerdi product is continuous, lapping corners and all, the plastic will be unnecessary.
if you think of tile like exterior cladding, it would make sense to leave an open hole in the sealant in line with a vertical joint in the grout.  porcelain and ceramic tile is impervious (some soft specialty limestone or sandstones are not), so any water that migrates does so in the grout joints (which crack on occasion as you know).  it should then hit the waterproofing and migrate down (however slowly) to the "weep" in the tile joint around the lip of the tub/shower.  ideally, you would install the vertical tile over vertically troweled mortar, which effectively provides little paths for the water to drain within the wall.  EIFS manufacturers have tried and tested this strategy such that it is their only warranted water management technique.
this is why you eventually see black mildew stains in the grout around the base of the tile - because the water is stuck back there.  the redguard product is a vapor retarder which means the steam (water vapor) from the shower won't migrate thru the substrate, it will hit the waterproofing and, assuming it condenses on the colder surface migrate down along the same path noted above.  in most instances, the tile is colder than the cement board, so the vapor condenses on it first and stays on the exposed surface.  rather than continuous plastic sheet.
as compromise, I would suggest a 6" high strip stapled above the flange and lapped over the flange and under the edge of the cement board is an adequate solution to prevent overflow situations.  probably unnecessary on a tub, but possibly on a shower pan.  then waterproof the walls, install the mortar with vertical troweled grooves, set the tile, wait, install sealant under each tile, stopping at each vertical joint for a small gap, plug the gap with a spacer before grouting, then fully grout, remove the spacers, and clean the tile.  the holes will look a bit odd at first, but will serve their purpose.
this comes from me, an architect, who spends a lot of time thinking about how to keep water out of a building.  I was told once "think like water" and you'll figure out where to let it out.
no flange provides a different challenge.  i'm about to rebuild my own shower with a tile floor and am thinking thru these exact details before buying anything.  thanks for talking about it and making me think like water for an interior application.
Comment: +1 for "vertical tile over vertically troweled mortar".  Wish I had thought of this before I did my install.  However, when I asked here I got some different advice: https://diy.stackexchange.com/questions/40379/what-style-notched-trowel-should-i-use-to-lay-6x24-ceramic-on-a-shower-wall
Answer: Follow manufacturer's instructions first and foremost.  Also in places with hot humid climate vapor barrier on the inside wall causes more trouble than it fixes.
https://www.jameshardiepros.com/getattachment/98adb0c7-1bd1-49e7-a9d4-a8275d29ae4a/HardieBacker-Installation-Guide-English_Spanish-HB1710.pdf Note on page 4 "vapor barrier if local codes require."
https://codes.iccsafe.org/content/IRC2015/chapter-7-wall-covering R702.3.7 in regards to where a vapor barrier goes in wet rock.
leading to:
https://codes.iccsafe.org/content/IRC2015/chapter-7-wall-covering R702.7 note vapor retarders on the interior face are only specified for climate zones Marine 4 and up.
Ending at:
https://codes.iccsafe.org/content/IRC2015/chapter-11-re-energy-efficiency#text-id-9849023 N1107.1 note what climate zone you are in will determine local code.
These are all the dots your building inspector needs to connect to make said determination.
Note* Most wet board manufactures also require Hot Dipped Galvanized nails or equivalent.  (this is missed by most inspectors even)
Comment: Hello, and welcome to Home Improvement. Thanks for the answer; keep 'em coming. And, you should probably [take our tour](//diy.stackexchange.com/tour) so you'll know how best to contribute here.
Answer: Lowes recommends installing a plastic vapor barrier behind the backer board in addition to a paint-on barrier between backer and tile.  Source.
Comment: +1 for the reference, even though most well logiced advice seems to point to the contrary.
Answer: This is a much-delayed answer, but in case it might be useful to others, the first consideration needs to be the manufacturer's own testing and resulting instructions. Most of the answers above contradict what the cement board manufacturers themselves recommend, so if you use them, you're on your own. This includes applying various sealants between the board and the tile which Hardiebacker, for example, does not recommend for interior installations.
If you are working in new construction and have a building engineer involved in the design or construction phase of the project, it may be worth asking whether the wall design will be primarily drying to the interior or exterior. For example, if the cavity is going to be filled with sprayed-in, closed-cell foam, any moisture that gets into the cavity may have nowhere to go and the engineer may recommend an alteration to the manufacturer's instructions for typical installation in order to suit the particular circumstance.
Sealants do break down over time and if you're worried about bulk water eventually making it back through the joints in the board (where you do want to be leaving small gaps to allow for movement in the wall without cracking or dislodging your finish work), you can always use asphalt roofing felt behind the board, overlapped as on the roof, which can be used to redirect the water to the sill but which is not a very effective vapor barrier.
Also, make sure you're using the right thickness of board for the application. I have seen folks try to use nom. 1/4" board where nom. 1/2" board was specified by the manufacturer for the application.
Answer: I've set tile for decades, the old school method of lath, cement plaster and the tile.  We always installed some type of moisture barrier under the lath on the wall beforehand  it used to be 15lb felt, 60 minute paper, aqua bar paper etc.  The cement plaster could be as little as 1/2 inch thick to over an inch.  I can't see any harm in putting a vapor barrier under backer board,but your going to put hundreds of fasteners in it anyway, puncturing it everywhere.  Most tiles today are large format and are vitrious (waterproof) and are the first defense against moisture. If water is getting in back of the tile, there's an installation issue. I've torn out many old showers and surrounds that were installed in traditional ways and seldom seen any water under the tiles  except perhaps a shower pan
Answer: http://www.cityofsanmateo.org/DocumentCenter/View/200 gives some fairly good guidance.  There are several kinds of backer boards.  If it's a cement board, you need a vapor barrier, because cement retains moisture, which means the wood next to it is always damp.
Comment: It does retain moisture, but the advice given by others here is to move the waterproofing between the tile and cement board with products like Redguard or Ditra. If there's a waterproof barrier there, you do not want a second vapor barrier in the wall, that would create a trap for the moisture. Also, the linked advice appears to be for drain pans, where you can get away with less waterproofing behind the tile.


What is the point of putting a Rock on the comm with the Mantis?

Question: A couple times now, I've encountered a Mantis ship decorated with Rock body parts.  If I have a Rock crew member, I am given a blue option to put him on the comm with the mantis ship.  Every time I do this, there is still a fight and I get no obvious rewards increase at the end.
Usually a blue option avoids a fight or gives some other kind of benefit, but what does this one do for me?
Answer: There doesn't appear to be one, except for the unique text that occurs.  I've never had anything happen differently after choosing this option.
The FTL Wikia lists this event and the various outcomes, which lines up with what we've observed.  However, they also note that this event is sometimes buggy and may be incomplete.
Comment: Ah, I looked on the [main events page](http://ftlwiki.com/wiki/Events) and it is not listed.
Comment: @OrigamiRobot, yeah, that's the "official" wiki, there's also a Wikia site, which is where I found it.
Comment: I love it when the unofficial wiki is better than the official one...


How to check for end of input? C, find 42

Question: This is the problem:Your program is to use the brute-force approach in order to find the Answer to Life, the Universe, and Everything. More precisely... rewrite small numbers from input to output. Stop processing input after reading in the number 42. All numbers at input are integers of one or two digits.
Input:
1
2
88
42
99
My first code doesn't work:
while( scanf("%d\n", &n) != 42 ){
    printf("%d\n",n);
}

second code, with for loop, works but there is a test case where there is no number 42 so it returns TLE, how do I check for end of input?
for(i=1;i>0;i++){
    scanf("%d\n",&n);
    if(n!=42 ){       /* end of input??? */
        printf("%d\n",n);
    }
    else {
        break;
    }
}

And why doesn't while loop work like it should?
Comment: Read more about [`scanf`](http://en.cppreference.com/w/c/io/fscanf) and what it returns.
Answer: scanf returns the number of characters scanned, not the result.
So, write while loop as follows:
scanf("%d", &n);
while( n != 42 ){
    printf("%d\n",n);
    scanf("%d", &n);
}

Answer: Always good to avoid magic numbers.  Define a constant.
Check the result of scanf() (@Joachim Pileborg)
To check if the input is valid , test if scanf() result is 1 (1 format specifier correctly scanned).
To check for end of input, test if scanf() result is EOF.
while loop failure is well explained by @dbasic.  Roughly, scanf() reports the number of fields scanned, not the value scanned.
There is a lot to scanf().  If up to it, read the scanf() section of the C spec.  Where do I find the current C or C++ standard documents?
const int Answer_to_Life_the_Universe_and_Everything = 42;
int n;
int cnt;
// Use 2d to limit to 2 digits
while ((cnt = scanf("%2d\n",&n)) == 1) {
  if(n != Answer_to_Life_the_Universe_and_Everything) {   /* end of input? */
    printf("%d\n",n);
  }
  else {
    break;
  }
}
if (cnt != EOF) Handle_UnexpectedInput();  // example someone type in "junk"

Comment: You have some syntax errors but while ((cnt = scanf(%2d\n",&n)) == 1)  is what I needed


Android Fragment getArguments() returns null

Question: As the title suggest.
I've downloaded Fragment code from here, http://developer.android.com/shareables/training/FragmentBasics.zip.
It is Fragment example from Android Official Developer site. http://developer.android.com/training/basics/fragments/fragment-ui.html
This is the MainActivity.java's onCreate():
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.news_articles);

    // Check whether the activity is using the layout version with
    // the fragment_container FrameLayout. If so, we must add the first fragment
    if (findViewById(R.id.fragment_container) != null) {

        // However, if we're being restored from a previous state,
        // then we don't need to do anything and should return or else
        // we could end up with overlapping fragments.
        if (savedInstanceState != null) {
            return;
        }

        // Create an instance of ExampleFragment
        HeadlinesFragment fragment = new HeadlinesFragment();

        // In case this activity was started with special instructions from an Intent,
        // pass the Intent's extras to the fragment as arguments
        //fragment.setArguments(getIntent().getExtras());
        Bundle args= new Bundle();
        args.putString("category", "clothes");
        args.putString("item", "shirts");
        fragment.setArguments(args);

        // Add the fragment to the 'fragment_container' FrameLayout
        getSupportFragmentManager().beginTransaction()
                .replace(R.id.fragment_container, fragment).commit();
    }
}

And HeadlinesFragment.java's onCreate():
@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    // We need to use a different list item layout for devices older than Honeycomb
    int layout = Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB ?
            android.R.layout.simple_list_item_activated_1 : android.R.layout.simple_list_item_1;

    Bundle args = getArguments();
    if (args == null) {
        Toast.makeText(getActivity(), "arguments is null " , Toast.LENGTH_LONG).show();
    } else {
        Toast.makeText(getActivity(), "text " + args , Toast.LENGTH_LONG).show();
    }

    // Create an array adapter for the list view, using the Ipsum headlines array
    setListAdapter(new ArrayAdapter<String>(getActivity(), layout, Ipsum.Headlines));

}

I've read several QA here, like this one Fragment getArguments() returns null, and many other that related to setArguments() and getArguments(), but still I'm stuck.
And I've moved the Bundle and Toast code to onAttach() and to onCreateView() with no avail. What wrong with the my code? I think I'm missing something, but dunno what is it.
Please Help! Thanks.
Edit:
I'll state my intention more clearly. In FragmentBasic that I downloaded, there's MainActivity.java, HeadlinesFragment.java, and ArticlesFragment.java. The 'communication' from MainActivity.java to ArticlesFragment.java is not the problem here. What I want is to send data from MainActivity.java to HeadlinesFragment.java. Their connection's like this:
--------------------------------------
| MainActivity <-> HeadlinesFragment |
|      |                             |
|      |>> ArticlesFragment          |
--------------------------------------

And HeadlinesFragment is running at Runtime.
*These code works, when using Android gadget with < 600px width. But doesn't work when using on tablet ( >= 600px), As proved by @Tesla1984 below. But what I want is same result either on gadget < 600px and on gadget > 600px.
Comment: I've checked the code and `getArguments()` is not null. if the code above is your actual code , i don't think there is someting wrong. if not, check the variables?
Comment: @tesla1984: on what part you insert your code? in HeadlinesFragment.java or ArticlesFragment.java? Cause Wherever I put the `getArguments()` in HeadlinesFragment.java, I get null. Thanks.
Comment: Some times my eclipse+ADT fails!.. I need to clean project and rerun..
Comment: @ThammeGowda: Thanks for your input. I've reload it several times, with same result. Though, I didn't try it with others ADT version.
Comment: I've sometimes seen that using keys like "category" in Intent Extras do not work, whereas using keys of the format ".category" work. This happens only on a few phones and in just few scenarios.
Comment: I had the same problem. It seems like when the fragment is inflated in the xml, the getArguments() returns null. However, when the fragment is called inside the Activity-code, the getArguments() in the fragment is not null.
Comment: I had a similar issue, turns out I was overriding the setArguments() method and not actually setting the arguments
Answer: @tonny
I've download the FragmentBasics.zip. I only change the argument name. Here is the code and result pic.
MainActivity
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.news_articles);

    // Check whether the activity is using the layout version with
    // the fragment_container FrameLayout. If so, we must add the first fragment
    if (findViewById(R.id.fragment_container) != null) {

        // However, if we're being restored from a previous state,
        // then we don't need to do anything and should return or else
        // we could end up with overlapping fragments.
        if (savedInstanceState != null) {
            return;
        }

        // Create an instance of ExampleFragment
        HeadlinesFragment fragment = new HeadlinesFragment();

        // In case this activity was started with special instructions from an Intent,
        // pass the Intent's extras to the fragment as arguments
//            firstFragment.setArguments(getIntent().getExtras());
        //test
        Bundle args= new Bundle();
        args.putString("category", "clothes");
        args.putString("item", "shirts");
        fragment.setArguments(args);

        // Add the fragment to the 'fragment_container' FrameLayout
        getSupportFragmentManager().beginTransaction()
                .replace(R.id.fragment_container, fragment).commit();
    }
}

HeadlinesFragment
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    // We need to use a different list item layout for devices older than Honeycomb
    int layout = Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB ?
            android.R.layout.simple_list_item_activated_1 : android.R.layout.simple_list_item_1;

    Bundle args = getArguments();
    if (args == null) {
        Toast.makeText(getActivity(), "arguments is null " , Toast.LENGTH_LONG).show();
    } else {
        Toast.makeText(getActivity(), "text " + args , Toast.LENGTH_LONG).show();
    }

    // Create an array adapter for the list view, using the Ipsum headlines array
    setListAdapter(new ArrayAdapter<String>(getActivity(), layout, Ipsum.Headlines));
}

here is the result
Comment: Yes, looks like it works when using resolution < 600px. Please try it when using nexus7 AVD. Cause of course we want same result when using on tablet or on phone (>600px and <600px). Thanks
Answer: I had the same problem, but solved it :)
My problem was that I had the <fragment android:name=""> element in the Activity's XML layout. Therefore the onCreate() of the Fragment was called before the calls in Java code, thus not setting the arguments.
I removed the <fragment> element from my XML layout and it worked!
Answer: I've solved it. Looks like the only way to send data from MainActivity.java to HeadlinesFragment.java is from callbacks (If anybody else know other ways, please contribute, then we have some other ways beside this one, helping others with this kind of problem).
The main code from is MainActivity.java's function public Bundle getBundle() {}, then set the interface section on HeadlinesFragment.java, and add public Bundle getBundle();, and last, call it from HeadlinesFragment.java's onCreate.
What confuse me is fragment.setArguments(getIntent().getExtras()); on MainActivity.java's onCreate. They put that code there, and I believing it will works cause it's from Android Official Developer Guide and API http://developer.android.com/training/basics/fragments/fragment-ui.html, but it didn't work (now I believe that piece of code won't do anything). So, anyone who read the tutorial or sample from there, take it with a grain of salt!
Codes below, so everyone can understand it.
MainActivity.java:
    /*
 * Copyright (C) 2012 The Android Open Source Project
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package com.example.android.fragments;

import android.os.Bundle;
import android.support.v4.app.FragmentActivity;
import android.support.v4.app.FragmentTransaction;
import android.widget.Toast;

public class MainActivity extends FragmentActivity
        implements HeadlinesFragment.OnHeadlineSelectedListener {

    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.news_articles);

        // Check whether the activity is using the layout version with
        // the fragment_container FrameLayout. If so, we must add the first fragment
        if (findViewById(R.id.fragment_container) != null) {

            // However, if we're being restored from a previous state,
            // then we don't need to do anything and should return or else
            // we could end up with overlapping fragments.
            if (savedInstanceState != null) {
                return;
            }

            Toast.makeText(getApplicationContext(), "activity", Toast.LENGTH_LONG).show();

            // Create an instance of ExampleFragment
            HeadlinesFragment fragment = new HeadlinesFragment();

            // In case this activity was started with special instructions from an Intent,
            // pass the Intent's extras to the fragment as arguments
            fragment.setArguments(getIntent().getExtras());

            // Add the fragment to the 'fragment_container' FrameLayout
            getSupportFragmentManager().beginTransaction()
                    .replace(R.id.fragment_container, fragment).commit();
        }
    }

    public void onArticleSelected(int position) {
        // The user selected the headline of an article from the HeadlinesFragment

        // Capture the article fragment from the activity layout
        ArticleFragment articleFrag = (ArticleFragment)
                getSupportFragmentManager().findFragmentById(R.id.article_fragment);

        if (articleFrag != null) {
            // If article frag is available, we're in two-pane layout...

            // Call a method in the ArticleFragment to update its content
            articleFrag.updateArticleView(position);

        } else {
            // If the frag is not available, we're in the one-pane layout and must swap frags...

            // Create fragment and give it an argument for the selected article
            ArticleFragment newFragment = new ArticleFragment();
            Bundle args = new Bundle();
            args.putInt(ArticleFragment.ARG_POSITION, position);
            newFragment.setArguments(args);
            FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();

            // Replace whatever is in the fragment_container view with this fragment,
            // and add the transaction to the back stack so the user can navigate back
            transaction.replace(R.id.fragment_container, newFragment);
            transaction.addToBackStack(null);

            // Commit the transaction
            transaction.commit();
        }
    }

    public Bundle getBundle() {
        Bundle args = new Bundle();
        args.putString("category", "cloths");
        args.putString("item", "shirts");
        return args;
    }
}

HeadlinesFragment.java:
    /*
 * Copyright (C) 2012 The Android Open Source Project
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package com.example.android.fragments;

import android.app.Activity;
import android.os.Build;
import android.os.Bundle;
import android.support.v4.app.ListFragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.Toast;

public class HeadlinesFragment extends ListFragment {
    OnHeadlineSelectedListener mCallback;

    // The container Activity must implement this interface so the frag can deliver messages
    public interface OnHeadlineSelectedListener {
        /** Called by HeadlinesFragment when a list item is selected */
        public void onArticleSelected(int position);
        public Bundle getBundle();
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        Bundle bundle = mCallback.getBundle();
        Toast.makeText(getActivity(), "headline fragment " + bundle, Toast.LENGTH_LONG).show();

        // We need to use a different list item layout for devices older than Honeycomb
        int layout = Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB ?
                android.R.layout.simple_list_item_activated_1 : android.R.layout.simple_list_item_1;

        // Create an array adapter for the list view, using the Ipsum headlines array
        setListAdapter(new ArrayAdapter<String>(getActivity(), layout, Ipsum.Headlines));

    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle
                    savedInstanceState) {

        return super.onCreateView(inflater, container, savedInstanceState);
    }

    @Override
    public void onStart() {
        super.onStart();

        // When in two-pane layout, set the listview to highlight the selected list item
        // (We do this during onStart because at the point the listview is available.)
        if (getFragmentManager().findFragmentById(R.id.article_fragment) != null) {
            getListView().setChoiceMode(ListView.CHOICE_MODE_SINGLE);
        }
    }

    @Override
    public void onAttach(Activity activity) {
        super.onAttach(activity);

        // This makes sure that the container activity has implemented
        // the callback interface. If not, it throws an exception.
        try {
            mCallback = (OnHeadlineSelectedListener) activity;
        } catch (ClassCastException e) {
            throw new ClassCastException(activity.toString()
                    + " must implement OnHeadlineSelectedListener");
        }
    }

    @Override
    public void onListItemClick(ListView l, View v, int position, long id) {
        // Notify the parent activity of selected item
        mCallback.onArticleSelected(position);

        // Set the item as checked to be highlighted when in two-pane layout
        getListView().setItemChecked(position, true);
    }
}

Comment: the `getArguments()` method won't be `null` if you set the arguments. and i don't suggest you use the `callback` to get the `bundle`.
Comment: @tesla1984: Please read my question. And the code. The argument has been set. Did you tried to Run the code? With your added `setArguments()` and `getArguments()`? At First, I think that that is the way, with set-getArguments(), but I was wrong. Oh, and if you have the solution that works, please post it below. I'll accept your answer if the code's works and doesn't use callbacks.
Answer: It looks like you are inserting a key and value pair into your bundle. You probably need to reference the key value as in getArguments().getString(category);
According to the docs for putString: Inserts a String value into the mapping of this Bundle, replacing any existing value for the given key. Either key or value may be null.
Parameters
key  a String, or null
value  a String, or null
Comment: `String category = getArguments().getString("category");` you mean? Have tried it. It shows error, and the program will close. You can read this QA too. I take the Toast code example from there [Fragment getArguments() returns null] (http://stackoverflow.com/questions/14970790/fragment-getarguments-returns-null)


Determinant of a matrix and its basis

Question: Is the determinant of a matrix independent of the basis in which that matrix is expressed? For example, when expressing in matrix form a quantum mechanics operator, or when comparing the same matrix but in its diagonal form.
Every case I try, I find it is independent of the basis. But why? How can I prove it, or what counter example could I find?
Thanks in advance.
Answer: Yes, it's a consequence of Binet's theorem: $\det(AB)=\det(A)\det (B)$. Therefore \begin{align}\det(PAP^{-1})&=\det (P)\det(A)\det(P^{-1})=\det(P)\det(P^{-1})\det(A)=\\&=\det(I_n)\det(A)=\det (A)\end{align}
Comment: Thank you very much!
Answer: A linear transformation from a (finite dimensional) vector space to itself has a determinant. Once you put a coordinate system on your space this linear transformation also has a matrix representation. You can use the entries of this matrix and a certain formula to calculate the determinant of the linear transformation (we call this "the determinant of the matrix", but most of the time that's a red herring).
The determinant was there before the coordinate system, and thus the determinant cannot in any conceivable way depend on the coordinate system.
Comment: I can see a point being made for e.g. change-of-basis matrices having genuine matrix-determinants rather than linear-transformation-determinants, as they don't exist until you impose at least two coordinate systems on your space, and they don't really represent an actual geometric linear transformation. But then again, their determinants always cancel eachother out as pointed out in the other answer (and as they should according to my answer, otherwise something has gone terribly wrong). So you rarely have to actually deal with those determinants.
Comment: Also, many applications of matrices have square matrices that don't appear from linear transformations (like the adjacency matrices of graphs). There too you could argue that the matrix itself has a determinant, rather than inheriting one. But in pure linear algebra, I prefer to think as much geometry and as little arithmetic as possible, and thus we arrive at this answer.
Comment: Thank you very much for your answer, it is a nice way of seeing it

Determinant of a matrix and its basis


error:Constructor in class cannot be applied to given types

Question: Writing a code that takes a string being a phone number with letters in the place of numbers and then decodes that string into just numbers. When I'm writing my tester class it's telling me that the constructor from my other class cannot be applied to the given types in my test cases.
This is the main chunk of the code.
public class PhoneNumber
{
    String phoneNumber;
    String telNumber;
    public PhoneNumber(String num, String telNum)
    {
        phoneNumber = num;
        telNumber = telNum;
    }

    public String decodePhoneNumber()
    {
        //Takes string form phone number and decodes based on number pad
        //Find code that makes if statement not care about caps
        //so if a || b || c number[cnt] = 1 etc..
        for (int cnt = 0; cnt < phoneNumber.length(); cnt++)
        {
            char num = phoneNumber.toLowerCase().charAt(cnt);
            if ((num == 'a') || (num == 'b') || (num == 'c'))
            {
                //number is 2
                telNumber = telNumber + "2";
            }
            else if ((num == 'd') || (num == 'e') || (num == 'f'))
            {
                //number is 3
                telNumber = telNumber +"3";
            }
            else if ((num == 'g') || (num == 'h') || (num == 'i'))
            {
                //number is 4
                telNumber = telNumber +"4";
            }
            else if ((num == 'j') || (num == 'k') || (num == 'l'))
            {
                //number is 5
                telNumber = telNumber +"5";
            }
            else if ((num == 'm') || (num == 'n') || (num == 'o'))
            {
                //number is 6
                telNumber = telNumber +"6";
            }
            else if ((num == 'p') || (num == 'q') || (num == 'r') || (num == 's'))
            {
                //number is 7
                telNumber = telNumber +"7";
            }
            else if ((num == 't') || (num == 'u') || (num == 'v'))
            {
                //number is 8
                telNumber = telNumber +"8";
            }
            else
            {
                //number is 9
                telNumber = telNumber +"9";
            }
        }
        return telNumber;
    }
}

This is my test class:
public class TestPhoneNumber
{
    public static void main(String []args)
    {
        PhoneNumber ph1 = new PhoneNumber("1-800-ILOVENY");
        System.out.println("Decoded phone number: " +ph1.decodedPhoneNumber());
    }
}

The error is coming from line 5 in the test class.
Comment: Your `PhoneNumber`'s only constructor takes two string parameters.
Comment: Wow, simple oversight on my part. Been looking at a few different projects today so its been a long day. Can't believe I missed that.
Answer: PhoneNumber class constructor has two string arguments public PhoneNumber(String num, String telNum) pass another string arguments or create another constructor with one String arguments.
Intialize the object like this
PhoneNumber ph1 = new PhoneNumber("XXXXX","1-800-ILOVENY");

or create another constructor of one String arguments in the PhoneNumber class
public PhoneNumber( String telNum)
    {

        telNumber = telNum;
    }


Can I use an existing Ground Rod for Sub-Panel in Detached Garage (Meter box is using the rod currently)

Question: Two buildings: Home and Detached Garage (circa '04 US). Service comes in through a Meter on the Garage to a PVC conduit into the Main box in the home (Single phase 240V with Neutral). In the main box Neutral and GND are bonded and bare ground wire coil heads out somewhere towards the front of the house, presumably to a ground rod.
There is an additional PVC conduit from the main panel back to the garage with 2 Hot, Neutral, and Ground that is used as two 120V runs (opposite phase), one for lights one for outlets and no sub-panel.
I'm planning on putting a 240V outlet in the garage and increasing the conductor side for 50A service. I will replace the two 120V breakers in the main panel with a 240V breaker and pull new wire (6ga x3 and 10ga Gnd) to a new sub-panel. From the sub-panel I'll wire back in the lights/outlets and the new service. Ground and Neutral will not be bonded and I know I need at least one grounding rod on this panel.
So finally I get to my question: There is an existing grounding rod that is being used by the Meter and apparently nothing else. Can I just add a new ground rod clamp to use with the sub-panel? Any code I'm violating?
Comment: NEC  250.130. (A,B,C) is the code reference that allows this.
Answer: You must tie to the existing grounding rod...
Since there's a rod present there already, you must tie your new subpanel's grounding electrode conductor to it, as per NEC 250.50 and the reference to Part III of Article 250 in NEC 250.30(A).
...and may be required to drive a second
If your existing rod is judged not to meet the 25ohm standard in NEC 250.53(A)(2), or if the AHJ wishes it, you may need to drive a second grounding rod 6-8' away (or more, if you wish) from the first.
You can either tie to the existing grounding electrode conductor with a 6AWG copper wire and an appropriate tap connector, or simply run the new rod's grounding electrode conductor back to the grounding bar on the subpanel, though.
Comment: I read 250.64(F)(2) to mean that, as an alternative to tying the new rod to the existing grounding electrode conductor with an appropriate tap connector, it's also allowed to install a new grounding electrode conductor from the new rod all the way back to the panel. Do you read it the same way?
Comment: @GregHill -- the issue is that you'd still have to tie the new rod to the existing rod in that case
Comment: Maybe I could be more clear - I interpreted that section to mean that 2+ GEC could be independently home-run. Each rod would connect to its own #6 wire; both wires would land on the ground bar in the panel. That's OK, isn't it? A few extra dollars/feet of #6 wire to run the second wire all the way to the panel seems like a no-fuss way of getting the job done - if it's acceptable.
Comment: @GregHill -- yeah, you could run a GEC to a new rod then a GEC to the existing rod
Comment: Just to clarify code separation of 8' or longer driven grounding electrodes is 6' or more if you want them 12' apart that is actually better.
Answer: As far as code it is allowed to add your clamp at the rod and use that for the new panel. If there are no breakers in the panel just the meter the only folks that could squak about it would be the power company. Sometimes the utility can be funny but if you have breakers there it is required so you would be fine. I would do it and I carry a couple ground rods on the van when I do service calls. Code specifically allows this
Comment: OK, let's face it....not all inspectors are created equal.  Much of what gets called out is dependent upon the experience and knowledge of the inspector. When I built my house I did all utility (power, cable, telephone) terminations at a small pump house.   It had a sub-panel in it to run the pump, lights, outlets, water softener, irrigation controller, and battery tender and heater for the standby generator. I ran a "tap" from one of the 200 amp lines to the sub-panel. I did it according to code, but had to "school" the inspector on chapter and verse of the NEC that allowed it.
Comment: Because the sub panel is new work, and the grounding electrode system at the detached building has one rod, isn't a supplemental electrode (or a 25-ohm test) also required by 250.53(A)(2)? (2017 NEC numbering)
Comment: I have never been required to have a second rod on a 4 wire feed , the 1 time the inspector asked I checked it and it was 15ohms he said that makes sense the further your rods are separated the better the ground. With a multi point tester like I have I would just string the electrodes towards the house and probably even pass in the desert. I should mention he knew I had the tester and had not required a second rod previously this was in early 18 after the 17 code was adopted, I believe any 4 wire feed will pass as the code only specified 25 ohms not the direction of the test.
Comment: Interesting... I happen to be in the midst of a branch-circuit-to-feeder upgrade not unlike the one OP describes. When I filed for the building permit the plan inspector specifically mentioned he'd expect to see two rods installed. I guess you're usually getting off easy with neither the test nor the extra rod, whereas my inspector is going to be very by-the-book.
Comment: continuing (sorry, but ran out of space).  The inspector didn't initially believe I wired the house bc I'm the owner, not an electrician. But after talking with  him he realized I knew what I was doing and only had a couple of minor findings (I missed a couple of AFCIs) and outlet spacing was off by too much in one area.


How to create list of dropdowns, each displaying a pre-selected object from a subset array, but having a superset array of object options

Question: I have a subset list of chosen operations, currentOps. i have another superset list of all operations, jsonOperations, that contains all chosen operations.
I want to display each item in currentOps as pre-selected in its own dropdown, but the user can change each value of currentOps to any item from jsonOperations using each dropdowns' lists.
My attempt so far:
<template>

            <option v-for="(jsonOperation, optionIndex) in jsonOperations" :key="optionIndex" :value="jsonOperation">
                {{ jsonOperation.name }}: {{ jsonOperation.type }} - {{ jsonOperation.active ? 'active' : 'inactive' }}
            </option>

</template>

currentOps array of objects, followed by an object item in jsonOperations array:

What it looks like right now:

What I want it to look like upon loading page:

Any help would be appreciated. Thank you
Answer: <template>

      <option v-for="(jsonOp, j) in jsonOperations" :key="jsonOp.id" :value="jsonOp.id">
        {{ jsonOp.name }}
      </option>

</template>


Android MediaCodec dequeOutputBuffer always returns -1

Question: I am using the new MediaCodec API on Jelly Bean to decode an h264 stream.
Using the code snippets in the developer page , instantiated a decoder by name (taken from media_codec.xml), passed a surface and configured the codec.
The problem I am facing is, dequeOutputBuffer always returns -1.
Tried with a negative timeout to wait indefenitely, no luck with that.
Whenever I get a -1, refreshed the buffers using getOutputBuffers.
Please note that the same issue is seen when a custom app is used to parse the data from a media source and provide to decoder.
Any inputs on the above will be helpful
Comment: Can you please post your code. I would be happy to debug it further
Comment: Examples of mediacodec usage: http://bigflake.com/mediacodec/
Answer: I had faced same problem. Incrementing presentationTimeUs parameter of queueInputBuffer()  on each call solved the issue.
For example,

codec.queueInputBuffer(inputBufferIndex, 0, data.size, time, 0)
time += 66 //incrementing by 1 works too

Answer: If anyone else is facing this problem (as I did today) while starting with MediaCodec make sure to release the output codecs after you're done with them:
mediaCodec.releaseOutputBuffer(index, render);

or else the codec will run out of available buffers pretty soon.
Answer: It may be necessary to feed several input buffers before obtaining data in output buffer.
Answer: -1 is INFO_TRY_AGAIN_LATER, meaning the output buffer queue is still being prepared and you just need to call dequeueOutputBuffer again.
Try using a work loop that calls dequeueOutputBuffer in a loop similar to ExoPlayer:

    while (drainOutputBuffer(positionUs, elapsedRealtimeUs)) {}
    if (feedInputBuffer(true)) {
      while (feedInputBuffer(false)) {}
    }

where drainOutputBuffer is a method that calls dequeueOutputBuffer.


Using MultipartEntityBuilder to upload files

Question: I have some existing Java code to upload files (as byte arrays) to Box.net, and recently I thought it would be good to upgrade the code to Apache HttpClient 4.4. However, this has been proving a little harder than expected. Here is my working legacy code:
HttpPost postMethod = new HttpPost(url);
MultipartEntity multipartEntity = new MultipartEntity();
for (NameValuePair parameter : parameters) {
    String parameterName = parameter.getName();
    String parameterValue = parameter.getValue();
    StringBody valueBody = new StringBody(parameterValue, ContentType.MULTIPART_FORM_DATA);
    multipartEntity.addPart(parameterName, valueBody);
}

Iterator iterator = byteArrayHashMap.keySet().iterator();
while (iterator.hasNext()) {
    String key = (String) iterator.next();
    byte[] byteArray = byteArrayHashMap.get(key);
    multipartEntity.addPart(key, new ByteArrayBody(byteArray, key));
}

postMethod.setEntity(multipartEntity);

and here is the new code:
HttpPost postMethod = new HttpPost(url);
MultipartEntityBuilder multipartEntityBuilder = MultipartEntityBuilder.create();
for (NameValuePair parameter : parameters) {
    String parameterName = parameter.getName();
    String parameterValue = parameter.getValue();
    StringBody valueBody = new StringBody(parameterValue, ContentType.MULTIPART_FORM_DATA);
    multipartEntityBuilder.addPart(parameterName, valueBody);
}

Iterator iterator = byteArrayHashMap.keySet().iterator();
while (iterator.hasNext()) {
    String key = (String) iterator.next();
    byte[] byteArray = byteArrayHashMap.get(key);
    multipartEntityBuilder.addBinaryBody(key, byteArray);
}

postMethod.setEntity(multipartEntityBuilder.build());

When I run the new code, the server complains of a missing parameter. Am I using the MultipartEntityBuilder correctly?
Comment: In case anyone stumbles across this question, I was able to solve this by updating the addBinaryBody call to set the ContentType as follows: multipartEntityBuilder.addBinaryBody(key, byteArray, ContentType.DEFAULT_BINARY, key);
Answer: In case anyone stumbles across this question, I was able to solve this by updating the addBinaryBody call to set the ContentType as follows: multipartEntityBuilder.addBinaryBody(key, byteArray, ContentType.DEFAULT_BINARY, key);


Does Flash CS4 have an alternative to ASDoc?

Question: Does anybody know of a tool that will allow me to create ASDoc style documentation with a Flash CS4/AS3 application? From what I hear ASDoc only works with Flex.
Thanks
Answer: After researching this for a while, I decided that the best tool out there for automated AS3 documentation in Flash (not Flex) is NaturalDocs. I highly recommend it if you want JavaDoc style documentation in your Flash projects.
Answer: You can use ASDoc with FlashDevelop to document any AS3 source, whether its for Flex or Flash.  I've just done it myself for the first time.  Download a trial version of Flash Builder 4, which includes ASDoc--of course you could use Flash Builder itself, or even call ASDoc directly from the command line.  FlashDevelop offers a free route with a good user interface.  And for programming AS3, FlashDevelop is an absolutely superb IDE.


Drillthrough a column of a matrix

Question: I have the following page :

I want to click on the name of the agent to move to report with more details for an agent, this is a simplified example:

Can I include filters in the detailed target page ?If yes, can I add a clear filters butto?
In this matrix, can I format only the Agent name ? Make the color blue and the font underlined?
Answer:
Can I include filters in the detailed target page ?

Yes.  It's the nature of Drill-Through to carry the active filters from the source page to the target page.  If you want to include filters that aren't specifically included as drill-through filters, then there is a specific setting "Keep all filters" that governs this.  Your detail page can also have it's own set of slicers and filters that will be applied regardless of the context that comes through via drill-through actions.

If yes, can I add a clear filters button?

There's one native in the service.   You can also affect the filters using the filter pane.  And you can add a bookmark that will restore the page to some pre-set state (without filters) and assign that bookmark to a button.  That's a tiny bit different than removing filters, but for most folks it's close enough

In this matrix, can I format only the Agent name ?

Yes, but only in this simple case.  Look for the 'Row Headers' and control formatting there.  In Matrix visuals where there are hierarchal fields, they will all be colored by this setting so it will not just be agent names.   Another approach would be to apply editing to subtotals and mark 'include label' and then turn the subtotals off.   You would get color on the subtotal row, but it would show on every column.

Make the color blue and the font underlined

You can set the font color on 'Row Headers' to blue.  Underscore is not an option.

Drillthrough a column of a matrix


Syntax error near unexpected token 'then'

Question: I typed the code the same as The Linux Command Line: A Complete Introduction, page 369
but prompt the error:
line 7 `if[ -e "$FILE" ]; then`

the code is like:
#!/bin/bash
#test file exists

FILE="1"
if[ -e "$FILE" ]; then
  if[ -f "$FILE" ]; then
     echo :"$FILE is a regular file"
  fi
  if[ -d "$FILE" ]; then
     echo "$FILE is a directory"
  fi
else
   echo "$FILE does not exit"
   exit 1
fi
   exit

I want to figure out what introduced the error. How can I modify the code? My system is Ubuntu.
Comment: Check https://shellcheck.net. The question is a bit old but for anyone else encountering such syntax errors, shellcheck is a great tool.
Answer: There must be a space between if and [, like this:
#!/bin/bash
#test file exists

FILE="1"
if [ -e "$FILE" ]; then
  if [ -f "$FILE" ]; then
     echo :"$FILE is a regular file"
  fi
...

These (and their combinations) would all be incorrect too:
if [-e "$FILE" ]; then
if [ -e"$FILE" ]; then
if [ -e "$FILE"]; then

These on the other hand are all ok:
if [ -e "$FILE" ];then  # no spaces around ;
if     [    -e   "$FILE"    ]   ;   then  # 1 or more spaces are ok

Btw these are equivalent:
if [ -e "$FILE" ]; then
if test -e "$FILE"; then

These are also equivalent:
if [ -e "$FILE" ]; then echo exists; fi
[ -e "$FILE" ] && echo exists
test -e "$FILE" && echo exists

And, the middle part of your script would have been better with an elif like this:
if [ -f "$FILE" ]; then
    echo $FILE is a regular file
elif [ -d "$FILE" ]; then
    echo $FILE is a directory
fi

(I also dropped the quotes in the echo, as in this example they are unnecessary)
Comment: The reason you need a space is because [ is actually a command. Type `which [` and you will see that it is in /bin/. You can write any `if [...]; then` command as `if test ...`.
Answer: The solution is pretty simple.
Just give space between if and the opening square braces like given below.
if [ -f  "$File" ]; then

fi


How do you set state when navigating with TouchableOpacity react native

Question: I am using a TouchableOpacity and when I press it I want to set some state and then pass that state down as a prop when I navigate. However when I try it navigates before the state is updated. Here is my code:
import {TouchableOpacity} from 'react-native-gesture-handler';

type props = {
    route: any,
}

const Identity = ({route}: props) => {
    const [identity, setIdentity] = useState('')

    const navigation = useNavigation();

    const {name, date} = (route.params)

    const [loaded] = useFonts({
        Poppins_600SemiBold,
    });

    if (!loaded) {
        return null;
    }

    return (
        <SafeAreaView style={styles.container}>
            <PageIndicator currentPosition={2}/>
            <View>
                <Text style={{
                    marginTop: 100,
                    alignItems: 'center',
                    justifyContent: 'center',
                    fontFamily: 'Poppins_600SemiBold',
                    fontSize: 30,
                    paddingLeft: 30
                }}
                >
                    What's your gender?
                </Text>
                <View style={styles.row}>
                    <TouchableOpacity
                        style={styles.button}

                        onPress={() => {
                            setIdentity('Man');
                            navigation.addListener('focus', () => {
                                setIdentity('Man')
                            });
                            navigation.navigate('InterestedIn', {
                                name,
                                date,
                                identity
                            });
                        }}
                    >
                        <Text style={{
                            color: '#fc92c5',
                            fontFamily: 'Poppins_600SemiBold',
                            fontSize: 15,

                        }}
                        >
                            Man
                        </Text>
                    </TouchableOpacity>
                    <TouchableOpacity
                        style={styles.button}
                        onPress={() => {
                            setIdentity('Woman')
                            navigation.navigate('InterestedIn', {
                                name,
                                date,
                                identity
                            })
                        }}
                    >
                        <Text style={{
                            color: '#fc92c5',
                            fontFamily: 'Poppins_600SemiBold',
                            fontSize: 15,
                        }}
                        >
                            Woman
                        </Text>
                    </TouchableOpacity>
                    <TouchableOpacity
                        style={styles.button}
                        onPress={() => {
                            setIdentity('Other')
                            navigation.navigate('InterestedIn', {
                                name,
                                date,
                                identity
                            })
                        }}
                    >
                        <Text style={{
                            color: '#fc92c5',
                            fontFamily: 'Poppins_600SemiBold',
                            fontSize: 15,
                        }}
                        >
                            Other
                        </Text>
                    </TouchableOpacity>
                </View>
            </View>
        </SafeAreaView>
    );
}

export default Identity;

Here is where my code navigates to:
import React, {useState} from "react";
import {SafeAreaView, StyleSheet, Text, View} from "react-native";
import {useNavigation} from "@react-navigation/native";
import {useFonts} from 'expo-font';
import {Poppins_600SemiBold} from '@expo-google-fonts/poppins';
import {TouchableOpacity} from 'react-native-gesture-handler';
import PageIndicator from './PageIndicator';

type props = {
    route: any,
}

const InterestedIn = ({route}: props) => {
    const [interest, setInterest] = useState('')

    const navigation = useNavigation();

    const {name, date, identity} = (route.params)

   // console.log(name)
   // console.log(date)
    console.log("identity", identity)
    console.log(route.params)

    const [loaded] = useFonts({
        Poppins_600SemiBold,
    });

    if (!loaded) {
        return null;
    }

    return (
        <SafeAreaView style={styles.container}>
            <PageIndicator currentPosition={3}/>
            <View>
                <Text style={{
                    marginTop: 100,
                    alignItems: 'center',
                    justifyContent: 'center',
                    fontFamily: 'Poppins_600SemiBold',
                    fontSize: 30,
                    paddingLeft: 30
                }}
                >
                    Who do you want to date?
                </Text>
                <View style={styles.row}>
                    <TouchableOpacity
                        style={styles.button}
                        onPress={() => {
                            navigation.navigate('navigator')
                            setInterest('Men')
                        }}
                    >
                        <Text style={{
                            color: '#FFF',
                            fontFamily: 'Poppins_600SemiBold',
                            fontSize: 15,

                        }}
                        >
                            Men
                        </Text>
                    </TouchableOpacity>
                    <TouchableOpacity
                        style={styles.button}
                        onPress={() => {
                            navigation.navigate('navigator')
                            setInterest('Women')
                        }}
                    >
                        <Text style={{
                            color: '#FFF',
                            fontFamily: 'Poppins_600SemiBold',
                            fontSize: 15,
                        }}
                        >
                            Women
                        </Text>
                    </TouchableOpacity>
                    <TouchableOpacity
                        style={styles.button}
                        onPress={() => {
                            navigation.navigate('navigator')
                            setInterest('Everyone')
                        }}
                    >
                        <Text style={{
                            color: '#FFF',
                            fontFamily: 'Poppins_600SemiBold',
                            fontSize: 15,
                        }}
                        >
                            Everyone
                        </Text>
                    </TouchableOpacity>
                </View>
            </View>
        </SafeAreaView>
    );
}

export default InterestedIn;

And here is the console log:
    identity
Object {
  "date": 2002-04-03T23:00:00.000Z,
  "identity": "",
  "name": "Ol",
}

I tried to add an event listener to the navigation but that didnt work. Do you have any suggestions, or maybe better ways to give text to a touchable opacity rather than this way? thanks :)
Answer: You might use useEffect, based on the (documentation, that would look like this :
useEffect(() => {
    if (identity) {
        navigation.navigate('InterestedIn', {
             name,
             date,
             identity
        });
    }
});

Comment: Will that not navigate as soon as my component loads though?
Comment: I get this error if i do Error: Invalid hook call. Hooks can only be called inside of the body of a function component. This could happen
 for one of the following reasons:
1. You might have mismatching versions of React and the renderer (such as React DOM)
2. You might be breaking the Rules of Hooks
3. You might have more than one copy of React in the same app
Comment: You need to check that the state value you're interested in has changed before navigating. I updated the code sample, you might need to adapt it to suit your needs


JSTL SQL Update rowCount?

Question: Is it possible to count the rows affected from an sql update statement inside jstl?
I have tried to do this but it does not work.
Comment: .  And then i want to run a test to check if the update was successful. I have tried: reqConfirmBooking.rowCount != 1 and another test reqConfirmBooking.rowCount == 1
Answer: According to the JSTL TLD Docs, the var attribute specifies the name of the variable containing the row count, so as per your example
reqConfirmBooking != 0

should work.
Comment: Thank you! it worked. My mistake I did not need to add ".rowCount" to the end of the variable as the variable already held the number of rows affected!

JSTL SQL Update rowCount?


highcharts.js how to make double donut charts in one raw?

Question: I use Highsharts to render my image. Now I want to make two donut charts in same row just like this one.
jsfiddle: http://jsfiddle.net/wergeld/e2qpa/47/ jsfiddle
I have try to set container's width,but can't achieve that result. Below demo is the area where I stucked in now. So who can give me some advice? Thanks in advance !
jsfiddle: http://jsfiddle.net/lazybios/7nydybqa/ Demo-jsfiddle
Comment: Why you cannot place charts in any table, or set CSS styles which will position divs as grid?
Answer: Try:

Note the 'float:left'


Dependency injection of nest in babel particularly with mongoose

Question: I am following the guide of NestJs about Mongoose but with Babel and I'm facing an error trying to inject my schema. The code is pretty simple and it is just the same as the typescript examples but with babel.
This is my main module
import { Module } from '@nestjs/common';
import { MongooseModule } from '@nestjs/mongoose';
import { EventModule } from './events/event-module';

@Module({
  imports: [
    MongooseModule.forRoot(process.env.MONGO_URI),
    EventModule,
  ],
})
export class AppModule {}

This is the simplest schema example
import { Schema } from 'mongoose';

export const EventSchema = new Schema({
  title: String,
  description: Number,
});

The module event module:
import { Module } from '@nestjs/common';
import { MongooseModule } from '@nestjs/mongoose';

import { EventController } from "./event-controller";
import { EventService } from "./event-service";
import { EventSchema } from '../schemas/event-schema';

@Module({
  imports: [
    MongooseModule.forFeature([
      { name: 'Event', schema: EventSchema }
    ])
  ],
  controllers: [EventController],
  providers: [
    EventService,
  ],
})
export class EventModule {}

And finally, the service where I want the schema to be used:
import { Injectable } from '@nestjs/common';
import { InjectModel } from '@nestjs/mongoose';
import { EventSchema } from '../schemas/event-schema';

@Injectable()
export class EventService {
  @InjectModel(EventSchema) eventModel;
  async getAll() {
    return await this.eventModel.find().exec();
  }
}

The problem is that when I call getAll from the controller, it turns out that eventModel is undefined! No error is thrown at instantiation. The error thrown is:
TypeError: Cannot read property 'find' of undefined
    at EventService._callee$ (D:\.../event-service.js:9:34)
    at tryCatch (D:\...\node_modules\babel-polyfill\node_modules\regenerator-runtime\runtime.js:65:40)

Is it possible that in babel, the dependency injection works different for nestjs? How the InjectModel is supposed to work or how should it be used with babel?
Thank you very much in advance, any advice or tip is well appreciated and received
Regards
Comment: May try @Bind(InjectModel(EventSchema))
Comment: Does injecting into constructor work?
Comment: the contructor is not decorable, neither the arguments. The @Bind doesn't work with InjectModel
Comment: What do you mean by *constructor is not decorable*? Sorry if it is something obvious.
Answer: There has a error:
import { Injectable } from '@nestjs/common';
import { InjectModel } from '@nestjs/mongoose';
import { EventSchema } from '../schemas/event-schema';

@Injectable()
export class EventService {
  @InjectModel(EventSchema) eventModel;
  async getAll() {
    return await this.eventModel.find().exec();
  }
}

This line
@InjectModel(EventSchema) eventModel;

should be @InjectModel('Event') eventModel


Combine 2 Query sets and display Django

Question: Im new to django
I am trying to combing two query sets for example, I have different farms. and in those farms they have respective blocks.
I would like to output the farm as a heading and list the blocks of each farm underneath it.
Example:
Farm 1
Block 1
Block 2
Blaock 3
Farm 2
Block 1
Block 2
Block 3
What I currently in have in views:
def irrigation(request):

 obj3 = Farms.objects.all().values("id", "farm_name")
 obj2 = Blocks.objects.all()

 obj = obj2 | obj3

 context = {"object": obj}

 return render(request, "irrigation.html", context)

in html:
 {% for farms in object %}

 {{ farms.farm_name }} {{ farms.id }}
  Edit

 {% endfor %}

In models
class Blocks(models.Model):
 farm_id = models.CharField(max_length=100)
 block_name = models.CharField(max_length=255, null=True)
 block_size = models.CharField(max_length=255, null=True)
 block_concurrent = models.CharField(max_length=255, null=True)
 block_full_bloom = models.CharField(max_length=255, null=True)
 block_harvest_start = models.CharField(max_length=255, null=True)
 block_harvest_complete_date = models.CharField(max_length=255, null=True)
 block_log1 = models.CharField(max_length=255, null=True)
 block_log2 = models.CharField(max_length=255, null=True)
 block_log3 = models.CharField(max_length=255, null=True)
 block_crop_class = models.CharField(max_length=255, null=True)
 block_crop_type = models.CharField(max_length=255, null=True)
 block_crop_subtype = models.CharField(max_length=255, null=True)
 block_planted_date = models.CharField(max_length=255, null=True)
 block_plant_height = models.CharField(max_length=255, null=True)
 block_root_system = models.CharField(max_length=255, null=True)

class Farms(models.Model):
 farm_name = models.CharField(max_length=100)
 user_id = models.IntegerField(default='1')
 user_groups = models.JSONField(null=True)

Please help!
Comment: Can you share your models too
Answer: I found a solution using a foreign key.
Updated models:
class Blocks(models.Model):
 #farm_id = models.CharField(max_length=100)
 farm = models.ForeignKey(Farms, on_delete=models.CASCADE, default=None)
 block_name = models.CharField(max_length=255, null=True)
 block_size = models.CharField(max_length=255, null=True)
 block_concurrent = models.CharField(max_length=255, null=True)
 block_full_bloom = models.CharField(max_length=255, null=True)
 block_harvest_start = models.CharField(max_length=255, null=True)
 block_harvest_complete_date = models.CharField(max_length=255, null=True)
 block_log1 = models.CharField(max_length=255, null=True)
 block_log2 = models.CharField(max_length=255, null=True)
 block_log3 = models.CharField(max_length=255, null=True)
 block_crop_class = models.CharField(max_length=255, null=True)
 block_crop_type = models.CharField(max_length=255, null=True)
 block_crop_subtype = models.CharField(max_length=255, null=True)
 block_planted_date = models.CharField(max_length=255, null=True)
 block_plant_height = models.CharField(max_length=255, null=True)
 block_root_system = models.CharField(max_length=255, null=True)

Notice the line:
farm = models.ForeignKey(Farms, on_delete=models.CASCADE, default=None)

Farms stayed the same:
class Farms(models.Model):
 farm_name = models.CharField(max_length=100)
 user_id = models.IntegerField(default='1')
 user_groups = models.JSONField(null=True)

Then I ran the commands:
python manage.py makemigrations
python manage.py migrate

In views:
def irrigation(request):
 obj = Blocks.objects.all()
 context = {"object": obj}
 return render(request, "irrigation.htm", context)

To Output in html:
{% for blocks in object %}
{{ blocks.block_name }}
{% endfor %}

Combine 2 Query sets and display Django


Using print and lambda function with groupby

Question: I'm using a simple code. I try to see the result of a groupby by one column. But I have the problem that one of the results is duplicate.

#DataFrame
df = pd.DataFrame({'A': ['one', 'one', 'two', 'two', 'one'] ,
                   'B': ['Ar', 'Br', 'Cr', 'Ar','Ar'] ,
                   'C': ['12/15/2011', '11/11/2001', '08/30/2015', '07/3/1999','03/03/2000' ],
                      'D':[1,7,3,4,5]})

#Create a groupby and show the results

df.groupby['A'].apply(lambda x : print(x))

This show the result for one duplicate. What is the reason?
Comment: what is your expected output?
Comment: Sorry y expected
Comment: Sorry I expected , that show two dataframes one dataframe for A equal to "one" value and one dataframe for A equal to " two" value. Nevertheless this return three dataframes, for A equal to "one" the dataframe is duplicate
Comment: sorry the correct code is:
Comment: df.groupby(A').apply(lambda x : print(x))
Answer: From what I see, looks like you're looking for either one of the following:
df.groupby('A').apply(lambda x : x.sum())

OR
df.groupby(A').apply(lambda x: "{%s}" % ', '.join(x))

and I would recommend checking out this answer for more options: https://stackoverflow.com/a/17841294/6908282


Find the derivative of the root of cubic equation

Question: Consider the following cubic equation:
\begin{align}
\alpha ^3-2 \alpha ^2- \alpha(6+4x^2) +8 x^3-4x&=0
\end{align}
Where $x\in \mathbb{R}$.
The solutions $\alpha_1,\alpha_2,\alpha_3$ will depend on $x$. Solving this equation on Mathematica or Wolfram Alpha gives me complicated third roots.
I am not interested in the actual value of the roots, I am only looking for the value of $\frac{\mathrm{d}\alpha}{\mathrm{d}x}$. Does a method exist to obtain a "nice" expression for $\frac{\mathrm{d}\alpha}{\mathrm{d}x}$ without having to actually solve the cubic equation?
Edit:
Applying the advice from the answer, I obtain:
$$\frac{\mathrm{d}\alpha}{\mathrm{d}x}=\frac{(4 + 8 \alpha x - 24 x^2)}{(-6 - 4 \alpha + 3 \alpha^2 - 4 x^2)}$$
Is there a way to eliminate the $\alpha$ terms and have an expression $\frac{\mathrm{d}\alpha}{\mathrm{d}x}$ uniquely depending on $x$?
Answer: If you look at the determinant
$$\Delta=-1472 x^6+1152 x^5+2944 x^4+1408 x^3+1488 x^2-992 x+1008$$ it is negative except for $-1.3< x < 2.1$.
So, if you exclude this region, using the hyperbolic method for one real root, you have
$$\alpha=\frac{2}{3} \left(1+\sqrt{12 x^2+22} \cosh \left(\frac{1}{3} \cosh
   ^{-1}\left(\frac{-54 x^3+18 x^2+27 x+31}{\sqrt{2} \left(6
   x^2+11\right)^{3/2}}\right)\right)\right)$$
Write it as
$$\alpha=\frac{2}{3} \left(1+f(x) \cosh \left(\frac{1}{3} \cosh ^{-1}(g(x))\right)\right)$$ from which
$$\frac 32\frac{d\alpha}{dx}=f'(x) \cosh \left(\frac{1}{3} \cosh ^{-1}(g(x))\right)+$$ $$\frac {f(x)\,g'(x)}{3\sqrt{g^2(x)-1}} \sinh \left(\frac{1}{3} \cosh ^{-1}(g(x))\right)$$ Just a bit (!!) of patience.
Have fun. But, back to serious, enjoy the implicit function theorem.
Comment: What is the hyperbolic method? where can I Read about it?
Comment: @Buraian Have a look at  https://en.wikipedia.org/wiki/Cubic_equation#Hyperbolic_solution_for_one_real_root . This uses to give quite nice solutions. Cheers
Answer: Implicit function theorem to the resccue!
We have :
$$ F(x, \alpha) = 0$$
Say that $\alpha(x)$ that is alpha is some function of x around some nice local interval which keeps us on the zero set of F.. and then take derivative
$$ \frac{dF}{dx} = \frac{\partial F}{\partial x} + \frac{\partial F}{\partial \alpha} \frac{d \alpha}{dx}$$
Hence,
$$ \frac{d \alpha}{dx} = \frac{-\frac{\partial F}{\partial x} }{ \frac{\partial F}{\partial \alpha}}$$
With,
$$ F(x, \alpha) = \alpha ^3-2 \alpha ^2- \alpha(6+4x^2) +8 x^3-4x$$
I'll leave the computation up to you :-)

Going further, suppose we have a point on the curve $(x_o,\alpha_o)$ , then we can write a taylor expansion of $\alpha$ locally as:
$$ \alpha(x) = \alpha_o + \frac{d \alpha}{dx}|_{x_o,\alpha_o} (x-x_o) + \frac{1}{2!} \frac{ d^2 \alpha}{dx^2}|_{x_o,\alpha_o} (x-x_o)^2 + O \left( (x-x_o)^3 \right)$$
The catch is that this polynomial only behaves like a curve for some small segment of it (geometrically thinking). Also note that taking derivative of above polynomial yields $\frac{d \alpha}{dx}$ as a polnyomial in terms $(x-x_o)$
Comment: Right, yeah that's the problem with implicit curves. What you can do is write a taylor series expansion of $\alpha$ in terms of $x$ around some local neighborhood using the derivatives calculated from implicit function theorem (You can extend the theorem for higher derivatives as well.)
Comment: See [here](https://math.stackexchange.com/a/2041081/688539) and [here](https://math.stackexchange.com/a/3899889/688539) where I answered similar questions
Comment: Thanks, after computing $\frac{-\frac{\partial F}{\partial x}}{\frac{\partial F}{\partial \alpha}}$, the value depends still on $\alpha$ and $x$. Is there a way to eliminate the $\alpha$ term?
Comment: I have edited the answer, hopefully it's more complete now. I once did a 'set up' for the derivation for an extended implicit function theorem [here](https://math.stackexchange.com/q/3840137/688539), I never got an answer but I'm pretty sure you can use it for finding your derivatives
Answer: This answer will overlap alot with @Claude_Leibovici 's answer, but also covers the case when the cubic has 3 real roots.
Starting with Nickalls' parameters related to the geometry of the cubic, applied to your cubic:
$$\begin{align*}
        \alpha_N &= \dfrac{-b}{3a} = \dfrac{2}{3} \quad \text{(abscissa of inflection point)}\\
        \\
        \left[\delta(x)\right]^2 &= \dfrac{b^2-3ac}{9a^2} = \alpha_N^2 - \dfrac{c}{3a} = \dfrac{4}{3}x^2+\dfrac{22}{9}  \\
&\quad (\alpha\text{ distance squared from inflection point to turning point})\\
        \\
        y_N(x) &= f(\alpha_N) = \dfrac{2b^3}{27a^2} - \dfrac{bc}{3a} + d = 8x^3-\dfrac{8}{3}x^2-4x-\dfrac{124}{27}\\
&\quad \text{(ordinate of inflection point)}\\
        \\
        h(x) &= 2a\left[\delta(x)\right]^3 =2\left[\delta(x)\right]^3 = 2\left(\sqrt{\dfrac{4}{3}x^2+\dfrac{22}{9}}\right)^3 \\
&\quad \text{(y distance from inflection point to turning point)} \\
\end{align*}$$

The roots of your cubic, $\alpha_k(x)$, $k \in\{0,1,2\}$, can be expressed as a hyperbolic function of a complex hyperbolic angle, $\psi_k\left(\dfrac{-y_N(x)}{h(x)}\right)$, described in my short write-up here, based off of Nickalls' and Holmes' work:
$$\begin{align*}
        \alpha_k(x) &= \begin{cases}
                \alpha_N + 2\delta(x)\cosh\left[\dfrac{1}{3}\psi_k\left(\dfrac{-y_N(x)}{h(x)}\right)\right] \quad h(x) \ne 0\\
                \\
                \lim_{h(x) \to 0} \alpha_N + 2\delta(x)\cosh\left[\dfrac{1}{3}\psi_k\left(\dfrac{-y_N(x)}{h(x)}\right)\right] \\
\\
\quad \quad \quad=  \alpha_N + \sqrt[3]{\dfrac{-y_N(x)}{a}}\exp\left[\dfrac{1}{3}\left(i2k\pi\right)\right] \quad h(x) = 0 \\
        \end{cases} \\
\end{align*}$$
with
$$\begin{align*}
        \psi_k(u) &= i\theta_k(u)+ \phi(u)= \begin{cases}
                i(2k+1)\pi + \cosh^{-1}(-u) &  u \in \mathbb{R}, u < -1\\
                \\
                i2k\pi + i\cos^{-1}(u) & u \in \mathbb{R}, -1 \le u \le 1\\
                \\
                i2k\pi + \cosh^{-1}(u) &  u \in \mathbb{R}, u > 1\\
                \\
                i\left(2k+\dfrac{1}{2}\right)\pi + \sinh^{-1}(-iu) &  u \in i\mathbb{R}\\
        \end{cases} \\
\end{align*}$$
It's worth noting here that the input argument of $\psi_k(u)$, $u = \dfrac{-y_N(x)}{h(x)}$, is actually a discriminant between the case of 3 real roots and the other cases of 1 real root.
So to find your desired derivative
$$\begin{align*}\dfrac{d}{dx}\alpha_k(x)&= \dfrac{d}{dx}\left(\alpha_N+2\delta(x)\cosh\left[\dfrac{1}{3}\psi_k\left(\dfrac{-y_N(x)}{h(x)}\right)\right]\right)\\
\\
&=2\delta'(x)\cosh\left[\dfrac{1}{3}\psi_k\left(\dfrac{-y_N(x)}{h(x)}\right)\right]\\
\\
&\quad + 2\delta(x)\sinh\left[\dfrac{1}{3}\psi_k\left(\dfrac{-y_N(x)}{h(x)}\right)\right]\dfrac{1}{3}\dfrac{d}{d(-y_N/h)}\psi_k\left(\dfrac{-y_N(x)}{h(x)}\right)\dfrac{d}{dx} \dfrac{-y_N(x)}{h(x)}\\
\\
&=2\delta'(x)\cosh\left[\dfrac{1}{3}\psi_k\left(\dfrac{-y_N(x)}{h(x)}\right)\right]\\
\\
&\quad + 2\delta(x)\sinh\left[\dfrac{1}{3}\psi_k\left(\dfrac{-y_N(x)}{h(x)}\right)\right]\dfrac{1}{3}\psi_k'\left(\dfrac{-y_N(x)}{h(x)}\right)\\
\\
&\quad \quad \cdot \dfrac{y_N(x)h'(x)-h(x)y'_N(x)}{\left[h(x)\right]^2}\\
\\
\end{align*}$$
At this point, the computation of $\delta'(x)$, $y'_N(x)$, and $h'(x)$ should be fairly straightforward.
The derivative of the complex hyperbolic angle $\psi_k(u)$ is
$$\begin{align*}
        \psi_k'(u) &= \begin{cases}
                \dfrac{-1}{\sqrt{u^2-1}} &  u \in \mathbb{R}, u < -1\\
                \\
                \dfrac{-i}{\sqrt{1-u^2}} & u \in \mathbb{R}, -1 \le u \le 1\\
                \\
                \dfrac{1}{\sqrt{u^2-1}} &  u \in \mathbb{R}, u > 1\\
                \\
                \dfrac{-i}{\sqrt{1-u^2}}  &  u \in i\mathbb{R}\\
        \end{cases} \\
\end{align*}$$
Then all that's needed is substitution of all of those functions of $x$ into the expression for $\alpha_k'(x), k \in \{0,1,2\}$.

If you don't want to use the hyperbolic function expression for the cubic roots, then from Nickalls' 1993 paper, you can go with
$$\begin{align*}\alpha_0(x) &= \alpha_N + \sqrt[3]{\dfrac{1}{2}\left(-y_N(x)+\sqrt{\left[y_N(x)\right]^2-\left[h(x)\right]^2}\right)} + \sqrt[3]{\dfrac{1}{2}\left(-y_N(x)-\sqrt{\left[y_N(x)\right]^2-\left[h(x)\right]^2}\right)}\\
\\
\alpha_{1,2}(x) &= \alpha_N - \dfrac{1}{2}\alpha_0(x) \pm i\dfrac{\sqrt{3}}{2}\sqrt{\left[\alpha_0(x)\right]^2-4\left[\delta(x)\right]^2}\\
\end{align*}$$
So computing your desired derivatives:
$$\begin{align*}\alpha'_0(x) &= \dfrac{1}{3}\dfrac{\dfrac{1}{2} \left(-y'_N(x) + \dfrac{y_N(x)y'_N(x)-h(x)h'(x)}{\sqrt{\left[y_N(x)\right]^2-\left[h(x)\right]^2}}\right)}{\left[\sqrt[3]{\dfrac{1}{2}\left(-y_N(x)+\sqrt{\left[y_N(x)\right]^2-\left[h(x)\right]^2}\right)}\right]^2} \\
\\
&\quad + \dfrac{1}{3}\dfrac{\dfrac{1}{2} \left(-y'_N(x) - \dfrac{y_N(x)y'_N(x)-h(x)h'(x)}{\sqrt{\left[y_N(x)\right]^2-\left[h(x)\right]^2}}\right)}{\left[\sqrt[3]{\dfrac{1}{2}\left(-y_N(x)-\sqrt{\left[y_N(x)\right]^2-\left[h(x)\right]^2}\right)}\right]^2} \\
\\\end{align*}$$
$$\begin{align*}\alpha'_{1,2}(x) &= -\dfrac{1}{2} \alpha'_0(x)\pm i\dfrac{\sqrt{3}}{2}\dfrac{\alpha_0(x)\alpha'_0(x) -4\delta(x)\delta'(x)}{\sqrt{\left[\alpha_0(x)\right]^2-4\left[\delta(x)\right]^2}}\\
\end{align*}$$
Again, all that's needed is substitution of all of those functions of $x$ into the expression for $\alpha_k'(x), k \in \{0,1,2\}$.


"Subtype" is incompatible with union type

Question: I stole some JSON types from the Flow docs.
I input an array of strings - annotated Array<string> - to a function that outputs a promise with some JSON - annotated Promise<JSON>. However, the JSON type seems to be incompatible with Array<string>.
As I understand it, the above should be compatible, since JSON could be JSONArray which is Array<JSON>, where JSON could be string.
I made a simpler example than the one in my code, and the last line throws the same error. You can see it in action here
// @flow

type JSON = string | number | boolean | null | JSONObject | JSONArray
type JSONObject = { [key: string]: JSON }
type JSONArray = Array<JSON>

const stringArrayWithArrayAnnotation : Array<string> = ["foo"]

// Line below throws:
// array type
// This type is incompatible with
// union: string | number | boolean | null | JSONObject | JSONArray`
const stringArrayWithJSONAnnotation  : JSON = stringArrayWithArrayAnnotation

Answer: Array type is invariant docs: Array elements
type A = Array<number | string>;
declare var x: Array<string>;
const y: A = x // => error: number. This type is incompatible with string

so while string is a subtype of number | string, Array<string> is not a subtype of Array<number | string>


How to minimize the distance between the point $(-1,0)$ and the curve $y^2 - x^3 = 0$?

Question: Given the equation of  a curve : $y^2 - x^3 = 0$, it is demanded to find the shortest distance from the point $(-1,0)$ to this curve.
Here is what I tried:

solve the curve formula for $y$:
y²=x³
write the function of the distance between$(-1,0)$ and the curve:
d(x,y)=√((1+x)²+y²)
replaced in d $y^2$ with $x^3$ and squared $d(x,y)$:
x³+x²+2x+1=h(x)
attempted to find the minimum of $h(x)$:
h'(x)=3x²+2x+2
but this derivate never equals to zero, so couldn't find any minimum for the function $h(x)$ because it tends -∞ when $x$ tends to -∞

Then i tried with Lagrange multipliers and found:

$2y(1+λ)=0  \implies  λ=-1$ or $y=0$
I rejected $y=0$ because for y=0 gradient of $y^2-x^3$ isn't linearly independent which is one of the conditions to use Langrange method.
$3x^2+2x+2=0$ (same as $h'(x)$ so it doesn't have a solution)
So I'm stuck with is and don't know how to solve the question, any help ?
Comment: Do you mean from the point $(1,0)$?  Otherwise, the answer is a very simple $1\ \text{unit}$ and is evident by inspection and concavity.
Comment: The curve has a cusp at the origin, so it has no derivative there; this is going to give either method, which is dependent upon differentiation, a difficulty.  On the other hand.  If you look at a graph of the curve and the point you are given, it will be clear what the closest point on the curve to $ \ (-1 \ , \ 0 ) \ $ is.  [On the other hand, if the point is supposed to be $ \ (1 \ , \ 0 ) \ $ (as Andrew Chin suggests), then you need to find the points on the curve where the normal line to the curve passes through $ \ (1 \ , \ 0 ) \ \ . \ ]$
Comment: A minimum for a function can be at a critical point, or at an edge of the function's domain. Hint: The domain for $x$ is not $\mathbb{R}$.
Comment: So whenever the function isn't differential at a point and the constraint is satisfied (at this point) it could be the extrema and I shouldn't eliminate it completely? Ty aschepler I didn't find the minimum of h(x) because I forgot to set the condition on x>=0
Comment: @Jazmine is the point $(-1,0)$ or $(1,0)$?
Comment: It is actually (-1,0). But now I'm also wondering how to do it for (1,0)
Answer: Since this is tagged "multivariable calculus", you have presumably dealt with parametric curves.  We can get around the problem created by the cusp in this "semicubical parabola" by parametrizing it using $ \ x(t) \ = \ t^2 \ , \ y(t) \ = \ t^3 \ \ . \ $  The distance-squared function for a point on the curve to $ \ (-1 \ , \ 0) \ $ is then $ \ (x + 1)^2 + y^2 \ \rightarrow \ (t^2 + 1)^2 + t^6 \ \ , \ $ which is an even function with a single evident absolute minimum.
If the point instead should be $ \ (1 \ , \ 0) \ \ , \ $ the distance-squared function becomes $ \ (t^2 - 1)^2 + t^6 \ \ , \ $ which is again even and has a relative maximum at $ \ t \ = \ 0 \ $ and two (symmetric) absolute minima.  Both functions have derivatives which are a factor of $ \ t \ $ times a biquadratic function of $ \ t \ \ , \ $ making extremization reasonably simple.
ADDENDUM (2/18) --  For this point, the approach, mentioned in the comments, using normal lines to the curve also works:  at a point $ \ ( x \ , \ x^{3/2} ) \ $ on the curve, the line to $ \ (1 \ , \ 0 ) \ $ has slope $ \ \large{\frac{x^{3/2}}{x - 1} } \ $ which must equal the slope of the normal line $ \ \large{ -\frac{2}{3·x^{1/2}} } \ \ . \ $  Setting these equal produces a quadratic equation for which only one value of $ \ x \ $ is positive; symmetry of the curve about the $ \ x-$axis then gives the two points closest to $ \ (1 \ , \ 0) \ \ . \  $   This also shows why the Lagrange method was not helpful for $ \ ( -1 \ , \ 0) \ \ : \ $ because of the character of its concavity, the normal lines to the curve cannot pass through that point, indicated by the analogous quadratic equation $ \ 3x^2 + 2x + 2 \ = \ 0 \ $ having no real solutions.


Random Graph without K3,3 subgraph

Question:
Prove there is a constant $c > 0$ s.t. for every sufficiently large n, there exists a graph
with n vertices and at least $cn^{3/2}$ edges, but no K3,3-subgraph.
Hint: let p be a suitably chosen function of n, such that G(n, p) in expectation has at least on the order of $n^{3/2}$ edges. Then compute the expected number of K3,3-subgraphs. Lastly, delete one edge from each K3,3-subgraph.

I have the intuition to set $p(n)=1/n^{2/3}$ and I did compute the expected number of K3,3-subgraphs of a random graph with n vertices: there are $\frac 1 2 {n \choose 3} {n-3 \choose 3}$ unordered pair of disjoint subsets of 3 vertices, you simply want the 9 edges to
be present. Thus, the expected number is $\frac 1 2 {n \choose 3} {n-3 \choose 3}p^9$, which shows $p(n)=1/n^{2/3}$ should be correct.
However, I dont know how to use the result/intuition I got above and the hint to get a full proof. Any help is appreciated.
Comment: As there are on the order of $n^2$ possible edges, if $p(n)=n^{-2/3}$ you expect only $n^{4/3}$ edges to be present.  To use the hint you need $p(n)=n^{-1/2}$
Comment: can you specify a little why and explanation? is it because we need to delete one edge from each K3,3, subgraph so we need to double/half p(n)? but doubling/halfing it doesnt get us $n^{4/3}$ or $n^{1/2}$, thanks!
Comment: @jamesblack You're jumping ahead. If $p(n) = 1/n^{2/3}$, then how many edges would you expect there to be? Ross is saying that we'd expect only $\sim n^{4/3}$ edges, and not the $n^{3/2}$ edges that the problem requires. Hence your $p(n)$ is too small.
Comment: i dont get how to use p=n^(-1/2) as i try to plug that into the expected value above, but it does not go to 0
Comment: @RossMillikan i got E(x) being cn^3(/2) and number of edges being E(x) being cn^3(/2) using p(n)=n^(-1/2), but then how do these two  results connect after i delete one edge from each K3.3 subgraph to show the final  result?
Comment: Your last comment should not reuse $E(x)$ and $c$.  Both the expected number of edges and the expected number of $K_{3,3}$s are of order $n^{3/2}$ but the constant factors are different.  You can then subtract them and get something of order $n^{3/2}$
Answer: Your expression shows that there are the order of $n^6\ K_{3,3}$ subgraphs.  If you choose $p=n^{-1/2}$ the number of these that are found in the random graph is of order $n^6 \cdot (n^{-1/2})^6 \sim n^{3/2}$.  You also have the order of $n^2\cdot n^{-1/2}=n^{3/2}$ expected edges.  If the constant on the number of expected edges is higher than the constant on the number of $K_{3,3}$ subgraphs, you can delete one edge per subgraph and still have of order $n^{3/2}$ edges left.  $c$ can be the difference of these constants or smaller.
Comment: by subtracting them do you mean expected number of edges minus 1/9*expected number of K3,3?
Comment: No, you need to delete one edge per expected $K_{3,3}$ to make sure it doesn't appear.  The point is that there are a factor greater than $1$ more expected edges than $k_{3,3}$ so you have a number of order $n^{3/2}$ edges left.

Random Graph without K3,3 subgraph