Groovy groupBy on multiple properties and extracting only value

Question: Having a list of elements:
List list =  [
    [category: 'A', name: 'a' value: 10],
    [category: 'A', name: 'b' value: 20],
    [category: 'B', name: 'a' value: 30],
    [category: 'B', name: 'c' value: 40],
    [category: 'B', name: 'd' value: 50],
]

I want to transform it into a nested map:
Map map = [
    A: [a: 10, b: 20],
    B: [a: 30, c: 40, d: 50],
]

The only solution I have come up with is to do something like this:
list.groupBy(
    { it.category }, { it.name }
).collectEntries { category, names ->
    [(category): names.collectEntries { name, values ->
        [(name): values.value[0]]
    }]
}

However, I will have to deal with more than 2 levels of nesting in the future, and this approach will be unfeasible.
Is there any neat way to obtain the proper result in Groovy that will be more flexible?
EDIT:
By more than 2 levels of nesting I mean converting structure like:
List list =  [
    [category: 'A', subcategory: 'I', group: 'x', name: 'a', value: 10],
    [category: 'A', subcategory: 'I', group: 'y', name: 'b', value: 20],
]

Into:
Map map = [
    A: [I: [
        x: [a: 10],
        y: [b: 20],
    ]],
]

By adding nesting (depth) it would require more nested collectEntries calls, which will become unreadable.
Comment: Can you give an example of what your data will look like with multiple levels of nesting?  It's not clear if you have nested values that need to go into top-level categories, or if your results need to be nested, or something else.
Answer: I have found a neat solution to the problem by using Map's withDefault method and recursive Closure calls:
Map map = { [:].withDefault { owner.call() } }.call()
list.each {
    map[it.category][it.name] = it.value
}

Or for the second case:
Map map = { [:].withDefault { owner.call() } }.call()
list.each {
    map[it.category][it.subcategory][it.group][it.name] = it.value
}


A minimal generating set for the order relation of rationals and reals

Question: Does there exist a binary relation $R$ on $\mathbb{Q}$ such that the transitive closure of $R$ is the order relation $<$, and that the transitive closure of any proper subset of $R$ is not the order relation? My second question is the same thing, but with $\mathbb{R}$ instead of $\mathbb{Q}$.
Comment: Do you really need two separate questions for $\mathbb R$ and $\mathbb Q$? Can't you just show that, if a linearly ordered set with more than one element is dense in itself, then its order relation has no minimal generating set?
Comment: @bof Well, what is the proof of your claim?
Answer: I'll just spell out bof's argument from the comments.
Suppose $(L,<)$ is a dense linear order with more than one element. I claim that there is no minimal binary relation on $L$ whose transitive closure is $<$.
Suppose $R$ is a binary relation on $L$ whose transitive closure is $<$. Since $L$ has more than one element, $R\neq \varnothing$. It suffices to show that for any $(a,b)\in R$, if we let $R' = R\setminus \{(a,b)\}$, then the transitive closure of $R'$ is also equal to $<$, since then $R$ is not minimal.
Since $(a,b)\in R$, we have $a<b$, and since $L$ is dense, there is some $c$ with $a<c$ and $c<b$. Since $<$ is the transitive closure of $R$, there exists $m\geq 0$ and $d_1,\dots,d_m$ with $a R d_1 R d_2\dots R d_m R c$ and there exist $n\geq 0$ and $e_1,\dots,e_n$ with $cR e_1 R e_2 R \dots R e_n R b$. Putting these together, and noting that no instance of $R$ in either chain is $(a,b)$, we have $$a R' d_1 R' d_2\dots R' d_m R' cR' e_1 R' e_2 R' \dots R' e_n R' b$$ so $(a,b)$ is in the transitive closure of $R'$. It follows that the transitive closure of $R'$ is equal to the transitive closure of $R$, which is $<$.


Firebase recycleAdapter duplicates objects in arrayList

Question: When I run this activity, it records the visible list objects to an array, but when I scroll down and go back up, it duplicates the elements again into the array. How to fix it? For an item to be added only once.
I have tried set but getting the same issue.
private void displayMessages(){

    final Set<ChatMessage> mSet= new HashSet<ChatMessage>();
    mChat = new ArrayList<>();

    mDBRootRef.child("messages").child(messageSenderId).child(messageReceiverId)
            .addValueEventListener(new ValueEventListener() {
                @Override
                public void onDataChange(@NonNull DataSnapshot dataSnapshot) {

                    for (DataSnapshot snapshot : dataSnapshot.getChildren() ) {
                        ChatMessage chat = snapshot.getValue(ChatMessage.class);

                        mSet.add(chat);

                    }

                    mChat.clear();
                    mChat.addAll(mSet);

                    MessageAdapter messageAdapter = new MessageAdapter(ChatActivity.this, mChat);
                    mUserMessagesListRV.setAdapter(messageAdapter);

                }

I have also tried .addChildEventListener instead of .addValueEventListener but getting the same issue.
Here is recycyleview initialisation.
    mUserMessagesListRV = (RecyclerView) findViewById(R.id.recyclerview_chat_log);
    mUserMessagesListRV.setHasFixedSize(true);
    LinearLayoutManager linearLayoutManager = new LinearLayoutManager(getApplicationContext());
    linearLayoutManager.setStackFromEnd(true);
    mUserMessagesListRV.setLayoutManager(linearLayoutManager);

Here is onBindViewHolder method.
@Override
public void onBindViewHolder(@NonNull MessageAdapter.ViewHolder viewHolder, int position) {

    //mChat is a list declared as private List<ChatMessage> mChat;
    ChatMessage chat = mChat.get(position);
    viewHolder.showMessage.setText(chat.getMessageText());
}

Comment: Have you tried to comment `mChat.addAll(mSet);`? What is the behaviour in this case?
Comment: Because we are clearing the list before mChat.addAll and then adding the set in a list.
Comment: Have you tried what I have asked you?
Comment: Yeah, still not working
Comment: **[This](https://stackoverflow.com/questions/49383687/how-can-i-retrieve-data-from-firebase-to-my-adapter/49384849)** is a recommended way in which you can retrieve data from a Firebase Realtime database and display it in a `RecyclerView` using `FirebaseRecyclerAdapter`.
Comment: You can also check **[this](https://stackoverflow.com/questions/48622480/showing-firebase-data-in-listview)** out.
Comment: Thanks. Let me check
Comment: Let us [continue this discussion in chat](https://chat.stackoverflow.com/rooms/185386/discussion-between-john-and-alex-mamo).
Answer: Btw it's strange that you didn't get concurrent modification exception. You can't remove from the list while iterating it:
 mChat = new HashSet<>();

  ....

   for (DataSnapshot ds : dataSnapshot.getChildren()) {
            for (DataSnapshot data : ds.getChildren()) {

               ChatMessage chat = snapshot.getValue(ChatMessage.class);
                mChat.add(chat);
            }
    }

Comment: I have tried HashSet but how can I get position in onBindViewHolder?
Comment: @Override
public void onBindViewHolder(@NonNull MessageAdapter.ViewHolder viewHolder, int position) {

        ChatMessage chat = mChat.get(position);

        viewHolder.showMessage.setText(chat.getMessageText());
}
Comment: @john  you could iterate through your HashSet and put just the strings you want into coordinate arraylists and use those to work your adapter. that would be better in terms of performance than dealing with the object themselves. If you don't want anymore objects, you should put a setPosition() method in each receipt then only take action in the getview if the correct getPosition() object matches the hascode you want but i think the first solution is much more straight-foward
Comment: Kindly have a look at my onBindViewHolder method (question edited). Am I doing something wrong there?
Comment: @john from hashset you can generate that in list after that for example:servicesList.addAll(mSet);
Answer: Really late to the party, but I've encountered the same problem, and it turned out to be that Listeners were kept attached to the Database reference even when I exited the Activity. So when I would reenter, it would essentially contain 2 listeners doing the same thing, thus duplicating RecyclerView members.
Try adding an extra getApplicationContext() argument when attaching a listener.
 mDBRootRef.child("messages").child(messageSenderId).child(messageReceiverId)
        .addValueEventListener(getApplicationContext(), new ValueEventListener() {
           // Do stuff
         }

This way, when you finish() your activity, the listeners attached to that very activity are detached from the database reference.
Comment: It returns an error when trying to add the context to addValueEventListener()


Installing Starlink on Old Sky Pole

Question: I'm getting Starlink in a few days and I've bought the pipe adapter for it.
I've removed an old sky dish to reuse the mount for it, LoS from here is excellent according to the app.

Firstly, should this be secure enough?
Secondly, what's going to be the best way to get the cable into the house? Drilling a 20mm hole through 80cm of whinstone doesn't sound fun... Reckon I can drop it into the loft somehow?
Comment: who installed that pipe on the right ?
Comment: Can you come through the window frame? It looks like wood so you might be able to drill a hole and pass the cable through a weather-sealed feed-through bushing mounted into the hole? Won't look... great, but'll work. Is there a reason you can't use the path for the old Sky cable?
Comment: @ruskes the PVC one?
Comment: @mjbraun, window frame isn't an option, the landlord would kill me, with the amount of holes for other cables going through the stone, he won't notice another, as for reusing the sky one, I don't think it will be big enough, there's quite a large connector on the end of the Starlink cable
Comment: Use the Sky cable hole as a pilot hole for your long 20 mm masonry bit (possibly involving tool hire) seems the best bet, at a guess. May be possible to go into the loft, but depends how things are built and what you can or can't do according to keeping the landlord happy. Does not look like you have good access at the edge of the roof. Very little exposed between the gutter and the wall
Comment: @Ecnerwal - Is there a specific type of drill I should be looking to hire?
Answer: If the new antenna is the same size, or smaller than, the old antenna, and the mount held the old antenna, it should hold the new antenna. If the new antenna is significantly bigger, (think wind loading more than mass) that becomes more of a judgement call on how over-engineered the old mount is.
I can't see anything that looks like a reasonable path into the loft in your pictures. A heavy duty masonry hammer drill and using the existing "Sky" cable hole as a pilot would be my best guess at doing this, with an appropriate long bit. Those will be "SDS, SDS-Plus or SDS-Max" in the current nomenclature for "serious" hammer drills, if you are going to hire one - with SDS-Max being the biggest and beefiest - though an alternative in hire equipment would be a suitable size core drill (diamond abrasive cutting a "ring" around the edge of the hole, not hammer-drilling) or just walk into (or call/email) your local tool hire shop and show them what you are up against, as I'm sure they are familiar with local construction and how best to get through it.
Comment: I did rent a drill... Lost the fight with the wall and very nearly snapped my wrist... The cable's gone in through the window and I've stuffed the gap with scarves... The dish is holding up nicely on the poll though

Installing Starlink on Old Sky Pole


How to avoid using random_id for Managed Instance Group creation in GCP

Question: Please help me to understand if I may avoid "random_id" using for Managed Instance group creation in GCP.
I know it is possible for the Unmanaged instance group where I can specify the exact names for instances.
But for MIG I always have some suffix with random_id
Answer: I think you can't and it's because the service needs a way to name instances that it creates. The service will use the template to create instances on-the-fly in order to maintain the number of instances that you define. Each instance requires a unique name.
A simple numbering system (could result in gaps and) would require the current number to be persisted.
Random suffixes are used because it's very improbable (but possibly, possible) for a random name to collide.
Conceptually (!) you should treat the instances as cattle not pets (link) too. You(r code) should not prefer a specific instance but should treat all the instances homogeneously.
Corollary: if you want to be able to refer to a specific instance, you probably shouldn't use a managed instance group.
With an unmanaged group you must either manually or via code maintain a list of named instances and so you can define the naming mechanism.
Answer: Stateful Managed Instance Groups support assigning names to each instance.
<code>gcloud compute instance-groups managed create-instance instance-group-name \
    --instance managed-instance-name \
    [--region region | --zone zone]
</code>
You can find more examples here.


Sets in Salesforce

Question: Accessing elements of a set.
If I have to access an element of a list , I can use the get() method . EX:- myList.get(1) would return the element at the 1st index.But the same seems invalid for sets. I am aware that set is an unordered collection. But does that mean that we cant access individual elements of a set?
Comment: As a side not, in order to get the first element, it would be `myList.get(0)`... now, in order to iterate over the set elements see: https://stackoverflow.com/questions/12455737/how-to-iterate-over-a-set-hashset-without-an-iterator If you have any specific doubt after reading that, update your question with the specific doubt/problem.
Comment: Possible duplicate of [How to Iterate over a Set/HashSet without an Iterator?](https://stackoverflow.com/questions/12455737/how-to-iterate-over-a-set-hashset-without-an-iterator)
Comment: We can, but in order decided by set's implementation. So unfortunately if you want to do it you would need to use iterator and iterate n times to get to n-th element. You can also copy current elements to list and then take them from it based on their index, but if set will change, list will not.
Answer: LIST class provides you the get method, but there is no get method in SET. As SET is an unordered collection, it is not certain to get the correct element in correct index.
The solution to this problem is, Cast the SET to LIST.
SET<String> str = new Set<String>();
str.add('4');
str.add('1');
str.add('2');
str.add('3');

string f = (new list<string>(str) )[0];
string s = (new list<string>(str) )[1];

You can get the element by index by this way.

Sets in Salesforce


Excel inetrop Graph printing

Question: I am printing a chart using excel inter OP in c#. The values are filled in the excel sheet and the graph is plot based on that. Every thing is working fine. when I am printing the graph, there is a problem in that The axis values are repeated. What will be a solution?
Comment: Looks like you have twice as many tick marks as you need, and the number format for your axis labels set to only whole numbers (making 0.5 show up as 1.0). Please include code if you want someone to figure out why this is happening.
Answer: I found the solution. It can easily done in excel by "format axis" option.

Excel inetrop Graph printing


Is Smash Ultimate the 5th or 6th Game in the Smash Bros. Series?

Question: I was reading the tag info for super-smash-bros-ultimate, which reads as follows:

A 2018 fighting game developed by Bandai Namco Studios and Sora Ltd., published by Nintendo for the Nintendo Switch. It is the fifth installment in the Super Smash Bros series.
(emphasis mine)

However, a friend of mine insists that Masahiro Sakurai, the creator, refers to Smash Ultimate as the sixth game in the series, since Smash for Wii U and Smash for 3DS were technically two different games. That being said, neither of us can find proof of this online (though we do see discussions about it like this one).
I know this may be trivial to my enjoyment of the game, but if I want to let my inner pedant shine, what number in the series is Super Smash Bros. Ultimate, technically?
Comment: After a lot of back and forth consideration, I ended up voting to reopen this as the fifth vote, as I disagreed that this *required* the developer to have said anything which is what the 'Developer Intent' close reason is for. This question still might be opinionated enough to be considered *'Primarily Opinion Based'*, (as there's arguments to be made for both sides) however, I'll leave that judgement to the community.
Answer: Sixth
According to Sakurai it is the sixth because in an interview in 2013 he refers to Smash for Wii U and Smash for 3DS as "versions four and five within the series".

Sakurai: No, actually, there was never any consideration to having him in previous games, and if you think about it, there hasn't been really a precedent for third-party characters joining other than very special cases like Sonic, during the last game. It's something that wasn't even possible. We're now going into versions four and five within the series—this is only something that's now possible.
Kotaku: When you say four and five, do you mean the 3DS and Wii U versions? Those are separate?
Sakurai: Yeah, exactly.
Kotaku: While we bring that up, how will those versions be different?
Sakurai: Essentially between the two versions the character structure is the same, and the moves shared between the characters are the same, but the stages are entirely different. On the 3DS, we've taken the motif of handheld games and then on the Wii U version, featured primarily stages based on games on console.
Kotaku: And how will they be able to connect, the 3DS and Wii U version? Will I be able to play against Wii U people if I'm using the 3DS?
Sakurai: It'll be possible, in fact, on the 3DS version there'll be a certain degree of character customization. You can have your own personalized character that you'll then be able to take over and move onto the Wii U version and play.
Kotaku: And you can also—on the 3DS version—play against people playing the Wii U version?
Sakurai: Actually, that's not possible. What is possible is for you to be able to customize your character, transfer it to the Wii U, and then play there. It would be technically impossible, just because the stages are so different between the two versions, so there isn't a situation where you have a handheld device and a console and you're able to play at the same time. Just more of a situation where there's integration, and [ability] to transfer data.
Kotaku, An In-Depth Chat With The Genius Behind Super Smash Bros.
Comment: I disagree with this. Typically, when the (mostly) same game is released on multiple consoles, they're not considered separate entries in the series.  Otherwise you could say there are eg. 50+ Resident Evil games - but no one is arguing that.
Comment: @All while the Sakurai "Word of God" is what I was looking for here, if you believe this answer isn't complete or entirely correct, I'd love to read an answer with a solid argument or some sources that takes the opposing stance that Ultimate is in fact the *Fifth* game.
Comment: @BlueRaja-DannyPflughoeft Completely agreed. Minor differences aside, the 3DS and Wii U versions of Smash 4 are two different versions *of the same game*. **It doesn't matter what Sakurai says.** "Word of God" doesn't apply here. The Smash series should be treated just like every other video game series. Smash UItimate is Smash 5. Period. Repeat: **It doesn't matter what Sakurai says.**
Comment: Seems lacking to not mention why the game is often referred to as the "fifth" entry. My impression is while quote is true, the community around the game hasn't taken to this. Referring to it as the sixth game is more likely then to be confusing.
Comment: @BlueRaja-DannyPflughoeft you should expand that into an answer :)
Answer: While I personally prefer to consider it to be the 5th game, technically it is the 6th, because 5 other entries came out prior to it. The confusing thing is that Super Smash Bros for 3DS is the 4th game and Super Smash Bros for Wii U is the 5th game, because they came out at different time, and although the games are practically identical, they have some differences, so they are considered separate entries. N64 is 1, Melee is 2, Brawl is 3, 3DS is 4, Wii U is 5, and Ultimate is 6.


Is it OK to have ground wire connected to breaker box wall instead of neutral bus?

Question: After having issues with lights flickering, I noticed the main 100A breaker was warm and arcing slightly. Instead of just replacing the breaker, I decided to call in a electrician to install a larger panel with spaces for more breakers, as I was planning to install an air conditioner in the future.
He said the existing ground wire wasn't long enough, so he connected it to the metal wall of the panel with something that looks like a miniature bus with one screw. (sorry, I forgot exactly what it was called)
Is it really safe to do this? Is there any advantage/disadvantage to connecting the grounding wire to the metal casing of the panel instead of directly to the neutral bus?
Comment: Most panels have a neutral bus and a ground bus both of which are connected to each other, the service entrance neutral, and the panel. All of this is bonded to the grounding electrode.  However, without knowing exactly what he did, what brand panel it is, and your location, it's impossible for us to tell you if it's acceptable or not.  If you could add some more information and a few pictures, that would help a lot.
Comment: Their should be a seperate neutral and ground bus in the panel and the panel box should be grounded to the ground bus.  The neutral and ground however should be connected by a wire as well.  The important thing is, if the main breaker is still warm and if your lights are still flickering.  Simply adding more slots for additional breakers and properly grounding your panel isn't going to fix this by itself.
Answer: The panelboard will be bonded to ground, and according to the National Electrical Code (NEC) it must be done so using specific methods.

250.8 Connection of Grounding and Bonding Equipment.
(A) Permitted Methods. Grounding conductors and bonding jumpers shall be connected by one of the following means:
(1) Listed pressure connectors
  (2) Terminal bars
  (3) Pressure
  connectors listed as grounding and bonding equipment
  (4) Exothermic
  welding process
  (5) Machine screw-type fasteners that engage not
  less than two threads or are secured with a nut
  (6) Thread-forming
  machine screws that engage not less than two threads in the enclosure
  (7) Connections that are part of a listed assembly
  (8) Other listed
  means
(B) Methods Not Permitted. Connection devices or fittings that depend solely on solder shall not be used.

If the specific method used in your situation fits one of the methods listed above, then the panelboard is likely grounded properly. The ground and neutral bus bars inside the panel are surely bonded to the panel itself using one of these methods. Which means as long as the panel is connected to the system grounding conductor using an approved method, the system should be properly grounded.
If you have doubts as to whether or not the installation is correct. Contact your local government and check on any permits that were obtained for the work, and/or request the installation be inspected by the local electrical inspector.
Answer: Nope, the box breaker wall is not designed to serve as a ground bus.
Yes, it is grounded so that if a stray wire falls onto the wall this incurs a leak or a short and protection trips but it is not meant to serve as the primary path to ground.
You have to extend the actual ground wire and use it as a ground.
So although from the common sense point of view you're perhaps okay (I've seen much worse installations and noone was shocked), the described installation violates the idea of how grounding is designed and so is not proper grounding.
Answer: Yes this is probably fine.  Usually grounds and neutral are connected to the same bus but if that is full you can add a ground bar that connects to the housing.
Only grounds should be connected to it though not neutrals.
For instance this Square D Catalog has a "Grounding Bar Kit" designed to add additional ground terminals to the Load Center.
This Instruction manual for the Grounding Bar kit shows that it may be installed with a single screw.
As mentioned in the comments both proper installation and a compatible grounding bar is required for it to be safe.
Comment: "probably fine", and electricity don't mix.  There is no way of telling if this installation is done properly without seeing it, so this answer is completely speculation.   Please provide some facts to support your statements.
Comment: I added links to specific products the can be used for this purpose.


Wiring mini split external and internal

Question: I am looking to install one of the MRCool DIY mini split in my garage.
I currently have a 30amp 240v break and have run 10 gauge wire to a 20amp receptacle for my air compressor.
Can I just use some wire connectors to splice in the box and add pigtails for my 20amp plug, then Come out of top of the box, drill through the wall and install my disconnect outside?  I found some WAGO brand "lever nut" connectors, those good?
How is the inside unit powered? In the instructions it mentions an "air brake switch" that looks like the internal unit is connected to but I can't find what amps or voltage that runs on.
Thank you
Comment: What breaker and wire size does the unit itself require?
Comment: Not strange at all. For every mini-split I've looked at in that level of detail, the inside units are powered from the outside unit. Thus the house power connects only to the outside unit. There might be some weird outliers, but that's what I've seen as "normal."
Comment: The outdoor unit will be labeled as to "minimum circuit ampacity" and "maximum overcurrent protection." Those are manufacturer requirements, chosen during the UL testing of the device, and electrical code requires those to be met. On the other hand, the use of a 20A receptacle protected by a 30A breaker violates electrical code. It may be possible that you could install a 30A receptacle and use the one circuit for both devices, but we'll need to know more about the labeled requirements for both machines.
Comment: Strange.  I looked at an installation guide for a MrCool mini-split i happened to have from a couple of years ago, and I can't find anything in there about power needs for the inside unit.
Comment: What do the instructions say?
Comment: @Ecnerwal - The unit I referenced has no power running between the inside and outside unit.  Only wires between those units are labeled "communications" or "signal".
Answer: You need to install and wire the equipment according to the labeling and instructions.  I'm not harshing on your asking a question, but note that that the following (and thus the reading) is a Code requirement.
There is already a harness of control wires running between the outdoor and indoor unit(s).  The interior unit powers nothing but a fan and some LEDs, so most mini-split installations simply throw fan power into that bundle. Thus it is powered from the outdoor unit.
20A receptacles on 30A breakers
That's a no-go.   The receptacle size must match the breaker size exactly for 20A, 30A and 50A breakers.  15A receptacles on 20A circuits are an exception, not a rule.
It's perfectly fine to use larger wire than is required, so the #10 is all good.
Further, the mini-split instructions are probably going to require a dedicated circuit.  And are probably going to require it be hard-wired.
A disconnect near the A/C.
Code requires a disconnect switch near the unit - as in line-of-sight near, not "other side of wall" near.
Instructions will also (most likely) specify a hard-wired connection with a disconnect.
Now, 'ratchet freak' suggesed a subpanel to split the 30A into dual 20A circuits (or 20A and 15A depending on the needs of the MrCool).  I totally agree. Note that a subpanel qualifies as a disconnect, so if the subpanel is placed outside near the unit, and feeds the compressor outlet back inside, we just crossed off the disconnect requirement :) "That was easy"
A 120V outlet is required within 25' of the unit
That is so the maintainer can plug in their vacuum pump. It is NOT required to be dedicated for the mini-split, it can be a general-use outlet.  Yes, I know the MrCool unit is DIY for initial installation, but it might need servicing later by a pro certified for handling refrigerants.  It's not just the certification, it's the required recovery equipment to prevent damage to the atmosphere, and the supply chain to recycle or destroy that refrigerant.
You cannot get 120V from a 240V circuit that you ran with /2 cable. (however if you ran /3 cable and you take it to a subpanel, you can stick a 120V breaker in the subpanel).  Feel free to  Extend some other shop circuit if needed.
Comment: I'm my case, an existing outdoor outlet covered that last requirement.
Comment: If I put the sub panel outside:  30amp breaker, 10 gauge wire, out the wall, into sub panel, then dual 20 amp breakers, can I send the wire back inside for my air compressor?
Comment: @user903805 Yeah, that's fine.
Comment: I was looking tonight at a unit with a 24k BTU compared to the 18k than I was originally thinking and  When checking the 24k manual it says: MCA:22 amps, MOP:35 amps. Minimum wire gauge for power cables: 8 min, 6 preferred. I'm guessing that means I have to run 8 gauge wire off a 40amp main breaker with a 35 amp breaker in the subpanel because the 10 gauge wire and 30amp I have now is below MOP?
Answer: HVAC equipment really likes being on a dedicated circuit as the compressor runs close to the cap of the circuit they are rated for. Most will require one, that includes a dedicated breaker.
What you can do is put in a mini subpanel that will split out the 30A circuit into 2 20A circuits, one to the receptacle and one to the outside unit (or a 30A for the outside unit and a 20A for the receptacle as needed). If you end up getting nuisance trips on the 30A breaker you can use a current sensor to lock out the compressor when the HVAC is drawing a lot of power.
How the inside unit is powered depends on the make and model. Many modern units run power and com wire from the outside unit to the inside unit alongside the refrigeration lines, other models will require an (likely 120V) outlet to power the inside unit and then run a low voltage com line between the units, some have the communication be wireless and only need an outlet at the inside unit. Check the manual.
Comment: I get the sub panel but can I just not run the compressor when I run the mini split and turn off the mini split when I run the compressor? I run the compressor honestly once a month if that. Id hate to do all the drywall cutting and additional costs for the sub panel and breakers
Comment: You can find surface mount subpanels especially in the 4-space class that you will need. And yeah you can use a manual select instead of an automatic lockout.
Comment: @user903805 - Regions vary but there are two good reasons not run the compressor and mini split on the same circuit: code violation and your home owner's insurance.
Comment: @user903805 you 'can' in that it may technically work. You *can't* however in that code is going to require individual circuits here.

Wiring mini split external and internal


What does [ ] stand for?

Question: I found this piece of code on StackOverflow:
[].sort.call(data, function (a, b) {})

Is [] a shorthand for "sort data values and then make an array with the same name"?
Comment: That simply initializes an empty array `[]`. It's also known as an array literal. See this: [stackoverflow.com/questions/1094723/](http://stackoverflow.com/questions/1094723/what-is-array-literal-notation-in-javascript-and-when-should-you-use-it) for more details...
Comment: probably need some more context for this line of code. As it stands right now it's not even valid javascript.
Comment: [] is an array and it is used here to call the sort on data that is not an array: https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/Function/call
Answer: [] is just array literal. It's an empty array, because it doesn't contain any elements. In this context it's a shortcut to Array.prototype.
This code basically allows you to use Array.prototype.sort() method even on values which are not arrays, for example arguments.
Further explanation:
[] // Array literal. Creates an empty array.
  .sort // Array.prototype.sort function.
  .call( // Function.prototype.call function
    data, // Context (this) passed to sort function
    function (a, b) {} // Sorting function
  )

Assuming that you have an array-like object, like this:
var obj = {0: "b", 1: "c", 2: "a", length: 3};

It's array-like, because it has numeric keys and length property. However, you can't just call .sort() method on it, because Object.prototype doesn't have such method. You can instead call Array.prototype.sort() in context of your object. That's exactly what Function.prototype.call() method is for. The first argument of .call() method is context passed to the function, and the rest are arguments passed to the function. For example:
Array.prototype.sort.call(obj)

returns sorted object, because Array.prototype.sort behaves like it was obj method.
Note that using Array.prototype is generally better practice than using array literal, because it's more explicit.
See also:

Function.prototype.call() docs
How does the "this" keyword work?
Array.prototype.sort.apply( someArray, args ) vs someArray.sort.apply( someArray, args )
How to sort javascript object array by element.name
What is array literal notation in javascript and when should you use it?

What does [ ] stand for?


$ \log_{\frac 32x_{1}}\left(\frac{1}{2}-\frac{1}{36x_{2}^{2}}\right)+\cdots+ \log_{\frac 32x_{n}}\left(\frac{1}{2}-\frac{1}{36x_{1}^{2}}\right).$

Question: Let $x_{1}$, $x_{2}$, $\ldots$, $x_{n}$ be $n$ real numbers in $\left(\frac{1}{4},\frac{2}{3}\right)$. Find the minimal value of the expression: $ \log_{\frac 32x_{1}}\left(\frac{1}{2}-\frac{1}{36x_{2}^{2}}\right)+\log_{\frac 32x_{2}}\left(\frac{1}{2}-\frac{1}{36x_{3}^{2}}\right)+\cdots+ \log_{\frac 32x_{n}}\left(\frac{1}{2}-\frac{1}{36x_{1}^{2}}\right). $
Answer: The expression equals to $2n$ when all $x_i=\frac13$.
The expression cannot be less than $2n$ because of AM-GM inequality due to the following:
$$\frac{\ln\left(\frac12-\frac1{36x^2}\right)}{\ln\left(\frac32x\right)}=2\frac{\ln\left(\frac94x^2-\left(\frac32x-\frac1{6x}\right)^2\right)}{\ln\left(\frac94x^2\right)}\ge2$$


"no suitable method found for add(java.lang.String)"in arraylist constructor?

Question: import java.util.ArrayList;
import java.util.Random;

public class College
{
    // instance variables - replace the example below with your own
    private ArrayList<Student> students;

    public College()
    {
        // initialise instance variables
        ArrayList<Student> students = new ArrayList<Student>();
        students.add("Student 1");
        students.add("Student 2");
        students.add("Student 3");

    }
}

basically it highlights the .add showing the error message "java.lang.IllegalArgumentException: bound must be positive", I don't understand what I did wrong here? I looked at a lot of these kinds of problem threads here but I did exactly what they did
Comment: Add your `Student` class to your post
Answer: You are adding Strings to a List parametrized to take Students.
Of course this is not going to compile.

Add a constructor to your Student class, taking a String argument (and the relevant logic within).
Then, use the following idiom: students.add(new Student("Student 1"));

To be noted, generics are there precisely to fail compilation at that stage.
If you had used a raw List (Java 4-style), your code would have compiled, but all sorts of evil would have happened at runtime, since you'd expect Student objects to be contained in your List, but you'd get Strings instead.
Answer: Can you show the code of the Student class? Like others have said, you have a Student arraylist and are sending a String instead. That is an invalid argument.
If your Student class takes a string to be initialized, you can try:
ArrayList<Student> students = new ArrayList<Student>();
students.add(new Student("Student 1"));

Answer: The ArrayList,  private ArrayList<Student> students can accept only Student objects.You are trying to add String to it.
If you want the list to accept String, define it like this: private ArrayList<String> student
Or, if you want the list to be of Student objects, then construct Student objects from the strings (how depends on the Student object) and add the object to list.
Comment: thank you i just realize what i did wrong now, thanks very much


Modify Apache Server Header Name

Question: I am using Ubuntu and i want to modify the header from "Server: Apache/2.2.22 (Ubuntu)" to "Server: MyName" How can i do this ? without using ModSecurity !
If possible please mention clear steps.
Answer: You can't without editing the source code, or installing something like ModSecurity, or putting something else in front of Apache.
Best you can do is change it to "Server: Apache" by adding the following to your Apache config:
<code>ServerTokens Prod
</code>
See ServerTokens documentation for more details.
It's been asked time and time again to allow this to be done in Apache in the change would be quite simple to do, but the Apache developers strongly disagree with this and say it adds no security value ("The idea of "security through obscurity" is a myth and leads to a false sense of safety.").
While the benefits of hiding this may well be overstated, many (myself included) disagree with Apache's stance here, and certainly disagree with the default setting for ServerTokens ("Full"). Some might argue its ego forcing you to keep "Apache" there.
Anyway, at same time ,I don't feel strongly enough about it to manually editing the source code, each time I upgrade, or to install anything else to work round their instance in (each of which could cause more issues), so live with just "Apache". Not that big a deal.

Modify Apache Server Header Name


concatenate using Underscore reduce?

Question: Could someone help me with this problem? I'm trying to use (Underscore) _.reduce to concatenate all strings in an array.
input:
['x','y','z']

output:
'xyz'

Here's how I started:
_.reduce(['x','y','z'], function(current, end) {
    return...
});

Comment: Not sure if this is helpful or not, but if you want to dig a little deeper into using fold (or reduce as Underscore calls it) check out this paper: http://www.cs.nott.ac.uk/~gmh/fold.pdf
Answer: You can simply use Array.prototype.join here. It would be more efficient than reduce for this case.
console.log(['x','y','z'].join(""));
// xyz

But if you want to use _.reduce, you can do it like this
_.reduce(['x', 'y', 'z'], function(accumulator, currentItem) {
    return accumulator + currentItem;
});
// xyz

_.reduce is just a wrapper over the native Array.prototype.reduce in environments which support it. You can understand how reduce would handle the input, from this answer, in detail.
Here is a short explanation.
Since there is no initial value passed to _.reduce, the first value in collection will be used as the accumulator value and the function is called with accumulator value and the second value. So, the function is called like this
accumulator : 'x'
currentItem : 'y'
-----------------
accumulator : 'xy' (because returned value will be passed again as accumulator)

and in the next call,
accumulator : 'xy'
currentItem : 'z'
-----------------
accumulator : 'xyz' (since no elements left, accumulator will be returned)

Comment: one question though... what do the function parameters mean exactly?  can they be any variables?
Comment: @RoryPerro I included a little more explanation. Please check that. Yes, the parameters can have any names (if that is what you are trying to ask)

concatenate using Underscore reduce?


PowerShell SharePoint Online ExecuteQuery Error - Timed Out

Question: This one has been puzzling me for days now... It works more than half the time, but will often give me this error upon calling the ExecuteQuery() command:

Exception calling "ExecuteQuery" with "0" argument(s): "The operation has timed out"

The PowerShell:
$ctx = New-Object Microsoft.SharePoint.Client.ClientContext($webURL)
$ctx.Credentials = New-Object Microsoft.SharePoint.Client.SharePointOnlineCredentials($Credentials.UserName,$Credentials.Password)

$web = $ctx.Web
$ctx.Load($web)

#Retrieve Library
$list = $ctx.Web.Lists.GetByTitle($ITPurchaseRequestListName)
$ctx.load($list)

$files = $list.rootFolder.files
$ctx.load($files)
$ctx.executeQuery()

##########
if((test-path $tempPath) -eq $False)
{
    new-item -itemtype directory -path $temppath
}

foreach($file in $files)
{
    $ctx.load($file)
    $ctx.executeQuery()

    $fileRef = $file.ServerRelativeURL
    $fileInfo = [Microsoft.SharePoint.Client.File]::OpenBinaryDirect($ctx, $fileRef);

    $fileName = $tempPath + $file.Name
    $fileStream = [System.IO.File]::Create($fileName)
    $fileInfo.Stream.CopyTo($fileStream);

    $fileStream.Close()

    start-sleep -seconds 2
}

If I kill the console session and start a new PowerShell window, it'll work for a few runs and then conk out again. Any ideas?
Answer: I think that calling executeQuery () with a foreach statement is not good for performance.
It is better to use "Include" to load the properties of the file object outside the foreach statement.
Reference URL
https://msdn.microsoft.com/en-US/library/office/ee539350(v=office.14).aspx#Anchor_5
Answer: In addition to the other comments and suggestions, the folks at 6sc.com were able to help me identify the root cause which was a missing stream.close() in the for loop.
foreach($file in $results)
{

    $fileRef = $file["FileRef"];
    $fileName = $tempPath + $file["FileLeafRef"];

    $fileInfo = [Microsoft.SharePoint.Client.File]::OpenBinaryDirect($ctx, $fileRef);
    $fileStream = [System.IO.File]::Create($fileName);
    $fileInfo.Stream.CopyTo($fileStream);

    $fileStream.Close();
    $fileInfo.Stream.Close();
}

Answer: Add a TRY..CATCH block to your PowerShell script and it will be handling the server time-out, which will provide continuity execution.
The other benefit of the TRY...CATCH, you will be able to have the details of the exception and you can capture on a separate log file, giving you additional clues about the problem. Right now it is hard to make an educated guess, files handles could be in use, server I/O, a file might be open in exclusive mode, connection might have been broken for a short time, hard to tell.
With the TRY..CATCH capturing the date and time + details of the exception will help you to open up Windows Event Viewer and find out with precision what happened.
Answer: I'd rather use .OpenBinaryStream(), download it into memory, and then save to disc.
Code:
foreach($file in $files)
{
    $data = $file.OpenBinaryStream();
    $ctx.Load($file);
    $ctx.ExecuteQuery();

    $memory = new-object system.io.MemoryStream
    $buffer = new-object system.byte[](1024*64)
    $pos = 0;
    while (($pos = $data.Value.Read($buffer, 0, $buffer.Length)) -gt 0)
    {
        $memory.Write($buffer, 0, $pos);
    }
    $memory.Seek(0, [System.IO.SeekOrigin]::Begin);

    $fileStream = [System.IO.File]::Create($fileName)
    $memory.CopyTo($fileStream)
    $memory.Close()
    $fileStream.Close()
}

Answer: include $fileInfo.Stream.Close(); that will do magic.


Ubuntu 14.04 on Mac using live USB gives corrupt display

Question: I have been trying to get Ubuntu to work on my desktop Macintosh running on OS X Yosemite but it doesn't seem to be starting up properly. I am using rEFInd to boot the USB, and I select Try Ubuntu without installing, and it all works up to now. As soon as the welcome screen pops up, I see four individual ubuntu screens. It also seem to be burning the pixels, and I cannot read the text on it.
Is there any way I can adapt the Ubuntu display for my mac?
I am using a desktop iMac (21.5-inch, from Late 2009). I am using a Mactel.
Answer: I have found a solution to my problem, after trying various different ideas (booting from DVD, changing USB drive etc.)
I tried installing Ubuntu 15.04 instead of Ubuntu 14.04 onto the live USB. This finally worked!


WPF INotifyPropertyChanged and INotifyCollectionChanged not being called

Question: I have implemented the INotifyCollectionChanged (probably incorrectly) and INotifyPropertyChanged for the individual items in my DataGrid.
I amend the data once the Window is renderes(ContentRendered="Window_ContentRendered" ) to see if the DataGrid gets updated.
I am having 2 issues.

When I call "priceLadderData.data.Values[0].ChangePrice(1);" I can see that OnPropertyChanged gets hit but no change is visible.
2.When I call "priceLadderData.AddRow(new PriceLadderRowData(99, 99));" I get the error below:

Exception: Information for developers (use Text Visualizer to read
this): This exception was thrown because the generator for control
'System.Windows.Controls.DataGrid Items.Count:5' with name 'dataGrid'
has received sequence of CollectionChanged events that do not agree
with the current state of the Items collection.  The following
differences were detected:   Accumulated count 4 is different from
actual count 5.  [Accumulated count is (Count at last Reset + #Adds -
#Removes since last Reset).]   At index 0:  Generator's item '[364525, WPF_PriceLadder.PriceLadderRowData]' is different from actual item
'[99, WPF_PriceLadder.PriceLadderRowData]'.   At index 1:  Generator's
item '[364550, WPF_PriceLadder.PriceLadderRowData]' is different from
actual item '[364525, WPF_PriceLadder.PriceLadderRowData]'.   At index
2:  Generator's item '[364575, WPF_PriceLadder.PriceLadderRowData]' is
different from actual item '[364550,
WPF_PriceLadder.PriceLadderRowData]'.   (... 1 more instances ...)
One or more of the following sources may have raised the wrong events:
System.Windows.Controls.ItemContainerGenerator
System.Windows.Controls.ItemCollection
MS.Internal.Data.EnumerableCollectionView   *     System.Collections.Generic.SortedList`2[[System.Single,
System.Private.CoreLib, Version=126.96.36.199, Culture=neutral,
PublicKeyToken=7cec85d7bea7798e],[WPF_PriceLadder.PriceLadderRowData,
WPF_Console2, Version=22.214.171.124, Culture=neutral, PublicKeyToken=null]]
(The starred sources are considered more likely to be the cause of the
problem.)
The most common causes are (a) changing the collection or its Count
without raising a corresponding event, and (b) raising an event with
an incorrect index or item parameter.
The exception's stack trace describes how the inconsistencies were
detected, not how they occurred.  To get a more timely exception, set
the attached property 'PresentationTraceSources.TraceLevel' on the
generator to value 'High' and rerun the scenario.  One way to do this
is to run a command similar to the following:\n
System.Diagnostics.PresentationTraceSources.SetTraceLevel(myItemsControl.ItemContainerGenerator,
System.Diagnostics.PresentationTraceLevel.High) from the Immediate
window.  This causes the detection logic to run after every
CollectionChanged event, so it will slow down the application.

MainWindow.xaml:
<Window x:Class="WPF_PriceLadder.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
        xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
        xmlns:local="clr-namespace:WPF_PriceLadder"
        mc:Ignorable="d"
        ContentRendered="Window_ContentRendered"
        Title="MainWindow" Height="450" Width="400">

    <Grid>
        <DataGrid x:Name="dataGrid"
                  HorizontalScrollBarVisibility="Hidden"
                  VerticalScrollBarVisibility="Hidden"
                  IsManipulationEnabled="False"
                  IsReadOnly="True"
                  AllowDrop="False"
                  CanUserAddRows="False"
                  CanUserDeleteRows="False"
                  EnableColumnVirtualization="True"
                  CanUserReorderColumns="False"
                  CanUserSortColumns="False"
                  CanUserResizeRows="False"
                  SelectionMode="Single"
                  FontWeight="Normal"
                  AutoGenerateColumns="False"
                  SelectionUnit="Cell"
                  >

            <DataGrid.Columns>
                <DataGridTextColumn Header="Price" Binding="{Binding Value.Price, UpdateSourceTrigger=PropertyChanged,NotifyOnSourceUpdated=True}">
                </DataGridTextColumn>

                <DataGridTextColumn Header="Volume" Binding="{Binding Value.Volume,UpdateSourceTrigger=PropertyChanged}">
                </DataGridTextColumn>
            </DataGrid.Columns>
        </DataGrid>
    </Grid>
</Window>

MainWindow.xaml.cs:
using System;
using System.Collections.Generic;
using System.Windows;
using System.ComponentModel;
using System.Runtime.CompilerServices;
using System.Collections.Specialized;

namespace WPF_PriceLadder
{
public partial class MainWindow : Window
{
    public PriceLadderData priceLadderData;

    public MainWindow()
    {
        priceLadderData = new PriceLadderData();
        FillUpWithDummyRows(priceLadderData);
        this.DataContext = priceLadderData;
        InitializeComponent();
        dataGrid.ItemsSource = priceLadderData.data;
    }

    public void FillUpWithDummyRows(PriceLadderData priceLadderData)
    {
        priceLadderData.AddRow(new PriceLadderRowData(364600, 37));
        priceLadderData.AddRow(new PriceLadderRowData(364575, 18));
        priceLadderData.AddRow(new PriceLadderRowData(364550, 30));
        priceLadderData.AddRow(new PriceLadderRowData(364525, 20));
    }

    public void Window_ContentRendered(object sender, EventArgs e)
    {
        priceLadderData.data.Values[0].ChangePrice(1);
        priceLadderData.AddRow(new PriceLadderRowData(99, 99));
    }
}

public class PriceLadderRowData : IComparable, INotifyPropertyChanged
{

    private float price;
    private int volume = 0;
    public event PropertyChangedEventHandler PropertyChanged;

    public float Price
    {
        get
        {
            return price;
        }
        private set
        {
            price = value;
        }
    }
    public int Volume
    {
        get
        {
            return volume;

        }
        private set
        {
            volume = value;

        }
    }

    public PriceLadderRowData(float price, int volume)
    {
        this.Price = price;
        this.Volume = volume;
    }

    public int CompareTo(object obj)
    {
        return Price.CompareTo(obj);
    }

    protected void OnPropertyChanged([CallerMemberName] string name = null)
    {
        PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(name));
    }
    public void ChangePrice(float price)
    {
        this.Price = price;
        OnPropertyChanged();
    }
}

public class PriceLadderData : INotifyCollectionChanged
{
    public event NotifyCollectionChangedEventHandler CollectionChanged;
    public SortedList<float, PriceLadderRowData> data = new SortedList<float, PriceLadderRowData>();

    public PriceLadderData()
    {

    }

    protected void OnCollectionChanged([CallerMemberName] string name = null)
    {
        CollectionChanged?.Invoke(this, new NotifyCollectionChangedEventArgs(NotifyCollectionChangedAction.Add));
    }

    public void AddRow(PriceLadderRowData priceLadderRowData)
    {
        this.data.Add(priceLadderRowData.Price, priceLadderRowData);
        OnCollectionChanged();
    }
}

}
Does anyone have any what is wrong here? No keyboard has been broken yet but I got close to it few times while learning WPF & XAML so I really appriciate your help.
Comment: Why did you invent your own thing rather than just using observablecollection? I would suggest whilst you're learning you use the things straight out the box first.  I also suggest you use a mainwindowviewmodel as datacontect of your mainwindow and bind itemssource rather than setting it. Also, remove UpdateSourceTrigger=PropertyChanged, The user cannot type anything in so it's pointless.
Answer: Question 1. Update of price.
When you are changing the price, you are calling OnPropertyChanged() in the ChangePrice() function. But the "[CallerMemberName]" used in OnPropertyChanged is getting the name of the calling function as the property name, in this case "ChangePrice". But the property name is "Price".
Normally OnPropertyChanged is called in the setter of the Price property:
   public float Price
    {
        get
        {
            return price;
        }
        private set
        {
            price = value;
            OnPropertyChanged();
        }
    }

Question 2. SortedList.
I agree with everyone else. Use an ObservableCollection instead. There are a lot of functionality that works with XAML.
But you want it sorted.
Here I have changed the PriceLadderData class to handle this:
(The purist will probably say that you should do it in XAML and you can, but here it is in code instead.)
public class PriceLadderData
{
    public ObservableCollection<PriceLadderRowData> data { get; } = new ObservableCollection<PriceLadderRowData>();

    public CollectionView dataView { get; private set; }

    public PriceLadderData()
    {
        dataView = (CollectionView)CollectionViewSource.GetDefaultView(data);
        dataView.SortDescriptions.Add(new SortDescription(nameof(PriceLadderRowData.Price), ListSortDirection.Ascending));
    }

    public void AddRow(PriceLadderRowData priceLadderRowData)
    {
        this.data.Add(priceLadderRowData);
    }

    public void Refresh()
    {
    //Refresh the sort order
        dataView.Refresh();
    }
}

Comments:
Added a CollectionView (dataView) which will be the sorted view of the data that will be bound to the DataGrid.
Set up the sort instructions for the dataView in the constructor of PriceLadderData.
Bind the dataView to the DataGrid in XAML:
    <DataGrid x:Name="dataGrid" ItemsSource="{Binding dataView}"

(remove the settings of ItemsSource in the MainWindow constructor)
If you are adding data or changing the sort key, you must refresh the sorting:
    public void Window_ContentRendered(object sender, EventArgs e)
    {
        priceLadderData.data[0].ChangePrice(1);
        priceLadderData.AddRow(new PriceLadderRowData(99, 99));
        priceLadderData.Refresh();
    }

You can also set a CollectionChanged event on data, but that will not take care of the situation when you only change a property.
If you want to change data in the DataGrid, you need to remove the "IsReadOnly=True" from the DataGrid and set that on the individual columns. You also need to remove the "private" on the propertys setter.
Comment: Thank you so much @RolandJS. I have been trying to figure this out for days. :-)
Answer: Your use of NotifyCollectionChangedEventArgs() is incorrect; you need to use the overload that takes newItems and oldItems and populate those.
Also, you're exposing your (should-be) encapsulated collection through the public data field. This is going to lead you down a bad path; it has already obscured the issue with the way you are calling the NotifyCollectionChangedEventArgs constructor. If you have calls in your code that look like x.y.z.w() you're doing something wrong.


Shower Water Handle central plastic core is stripped out - how to replace?

Question: After 15 years of use, the handle popped off my shower and the attaching screw (not pictured) will no longer thread in the central plastic part you see below.
The assembly does not leak, so can I replace just the plastic threaded part without pulling the whole cartridge?
Do I need a special tubular wrench type tool? The flat edge in the picture below (about 10 o'clock) makes me think that I'm seeing a special nut that can be taken off.
Also, does the house water need to be shut off for this particular procedure?
There are no brand names anywhere. The Delta & Moen videos on youtube aren't giving me any clues either.
Thanks!
Answer: The first thing I would try is getting a screw that's a little bigger and see if you can screw it in tight. If that piece was metal, I'd say tap a new thread but if it's plastic as you think it is, a self threading screw might do the trick.
If not, you'll have to replace the cartridge. That little central part can't be replaced, It's part of the cartridge. That outer sleeve should be removed, pull it straight out or turn it counterclockwise. Then use an adjustable wrench or a pair of Channelocs to remove the retaining ring for the cartridge and then remove the cartridge. The water to the shower has to be turned off to do this. If the shower doesn't have a shutoff behind the chrome cover, then the water to the house has to be turned off.
Comment: typo: it is a shower
Comment: that's what the local plumbing supply guy told me too - thanks!
Comment: once I found out that it was an Avante, I was able to find this video, which shows the whole procedure perfectly - https://www.youtube.com/watch?v=BBVm7J9OVuc
Answer: As a first approach, I'd probably put a thin coat of epoxy around the inside edges of the hole, then reassemble.  Goal is to get the screw to stay in and hold the handle on.
Comment: quite a lot of force is required to pull and push the handle on a daily basis - you've seen epoxy strong enough to handle that?


Increase size of some fonts in HL-2 Deathmatch

Question: I've just built a steamos machine and have HL2-Deathmatch running perfectly. Unfortunately some of the smallest fonts are too small to see on the TV  (highlighted in red):

How do I increase the size of these particular fonts?
**I changed every font size in ClientScheme.res (before I posted the question). Didn't solve the problem as far as I could tell... **
update It appears that the steampipe update may explain why editing clientscheme.res isn't working: http://steamcommunity.com/app/320/discussions/0/828937546133516432/
Comment: Related: [How do I adjust Steam chat font sizes?](http://gaming.stackexchange.com/questions/116537/how-do-i-adjust-steam-chat-font-sizes?rq=1), although it might answer your question
Comment: That seems to be related to steam UI. I have no problem with fonts in the UI part. It's just in HL-2 Deathmatch that some of the fonts are too small to read...
Comment: I agree it's a start...i've been looking through files galore. Was hoping for a simple solution. :)
Comment: I would have suggested that you lock (as if in NTFS) that file to external writing, as I have for a question relating changing Steam fonts. However I do not have experience in Linux and it would mean that ClientScheme is not only in charge of font size but that is is being overwritten every time you start the game.
Comment: nevertheless its a start, valve wrote both, perhaps HL has a similar setup to steam in regards to fonts?
Comment: I dont have a steambox, but most valve font settings are in a file called ClientScheme.res. Check out https://developer.valvesoftware.com/wiki/Authoring_and_Using_TrueType_Fonts
Comment: also related would be the 'showschemevisualizer // fonts and colors for a particular scheme. The default is ClientScheme.res' console command. http://www.gamerconfig.eu/commands/half-life-2-deathmatch/
Comment: I changed every font size in ClientScheme.res (before I posted the question). Didn't solve the problem was far as I could tell...
Comment: Guess I could try preventing that file being overwritten...chmod or something similar. Linux user here. :)
Answer: This will show you everything you need to know about modifying your HUD for HL2D: http://steamcommunity.com/sharedfiles/filedetails/?id=161652635
This article shows you how to modify the HUD using pretty simple CSS. You will find a README located here that shows you exactly what you need to change. how to change it and where to put it in your Steam folder.
Comment: Explain how that addresses the issue at hand in the answer.
Comment: Hi @ChaseC - we tend to avoid link-only answers as they may go missing, becoming useless. Could you summarise the steps presented in the walkthrough?
Comment: @Robotnik Yeah sure, sorry about that.
Comment: I believe that this won't work because of steampipe. (Plus I've edited res files left and right, but no change)...
Answer: This is an easy one :)
Open this page: http://hl2dm-maps.com/www/hl2/HUDTutorial.pdf and read it, which lasts less then 15 minutes (maybe you'll find other interesting edits on you hl dm)
However the most interesting part for you should be step 7 (and the introduction which announces the tools).
PLEASE do a backup of the files you alter, unless you want to reinstall the game in case you mess something up ;)
You fetch your ClientScheme.res and edit the values of "tall" for example for QuickInfo to 48.
Some machines have had problems using fontsizes which were not spcified in the fontfile.
So these following values should work fine: (20, 22, 24, 26, 28, 32)
And these should be big enough for your purposes: 36, 40, 44, 48, 54, 60, 66, 72, 80, 88, 96
One last thing: be careful with these files. Don't change the values too fast, as you do not know how the machine responds.
Comment: I have already tried editing the tall values of ClientScheme.res (as mentioned in the question)--several times now. Hasn't worked yet, so can't accept as an answer yet.
Comment: I'm sorry, i dont know how I did not see this :S
May you write down what happens if you alter this file?
As this tutorial helped a friend of mine half a year ago :)
I guess its a resolution caused problem
Comment: See the edit. Nothing happens when the file is edited. I believe this may be a steampipe issue.
Answer: Installing mscorefonts has made the smallest fonts slightly more readable:
<code>sudo apt-get install ttf-mscorefonts-installer
</code>
There are various guides on enabling Debian sources in SteamOS e.g., http://wp.xin.at/archives/1593
As for increasing the size of the fonts (making them much larger than standard), this appears to be a SteamPipe issue (which isn't solved with this solution).
tl;dr installing mscorefonts makes fonts slightly larger
Comment: Could you say, swap the offending font with an even larger-print one? As in, actually rename the font file
Comment: Possibly. But messing around with fonts like that is liable to mess up the system...
Comment: Hmm. I dunno about that. If a font couldn't be found it would just revert to the standard system font, plus so long as you keep a backup of the original file you can always revert if necessary. Up to you of course, its your system :-)
Comment: I had a look. I don't see how changing to another font is going to increase its size. mscorefonts are ttf files and the size is specified in the res files for HL2-DM. Changing ttf files is at best going to result in a different font of the same size? At least the fonts are readable now (with my solution) which is much better than it was. :)
Answer: You can try changing the resolution, making either a windowed or a smaller resolution when in full screen will make the hud (icons, visible text, etc) appear bigger and more readable. If not, send a support ticket to Valve.
Comment: I'm playing on the TV. I'm playing on 720 so changing the resolution is not an option (it's smaller at 1080). Also this is in Steamos..so windowed mode also isn't an option.


PHP rotated image is blank

Question: I'm using the following php code to save images from various devices. All works fine except iPhone images appearing sideways. I have found a way to fix this by rotating the image before it's saved. However when I upload the image it does not appear on my webpage and in my file manager it still appears sideways. Am I targeting the wrong file to rotate? Or am I using something else incorrectly?
Here's my code:
<code>    $file = $_FILES["newsnap"];
    $id = $_SESSION['id'];
    $username = $_SESSION['username'];
    $aboutitems = nl2br(mysqli_real_escape_string($database, $_POST['about-snap']));
    $uploadloc = mkdir("../$username/");
    $image_temp = $_FILES["newsnap"]['tmp_name'];//Temporary location
    $filename = mysqli_real_escape_string($database, htmlentities($file["name"]));

            $sourcePath = $image_temp; //  source path of the file

            $exif = exif_read_data($sourcePath);
            $orientation = $exif['Orientation'];

            switch($orientation)
                {
                    case 3:
                        $sourcePath = imagerotate($sourcePath, 180, 0);
                        break;
                    case 6:
                        $sourcePath = imagerotate($sourcePath, -90, 0);
                        break;
                    case 8:
                        $sourcePath = imagerotate($sourcePath, 90, 0);
                        break;
                }

            $targetPath = "../$username/$filename"; // Target path where file is to be stored

            move_uploaded_file($sourcePath, $targetPath) ; // Moving Uploaded file

            $added = date("y.m.d");

            mysqli_query($database, "INSERT INTO piqs(userid, chicpiq, aboutpic, added) VALUES('$id', '$targetPath', '$aboutitems', '$added')");
</code>
The code works perfectly fine without the below code. I added code below only to rotate a sideways image:
<code>            $exif = exif_read_data($sourcePath);
            $orientation = $exif['Orientation'];

            switch($orientation)
                {
                    case 3:
                        $sourcePath = imagerotate($sourcePath, 180, 0);
                        break;
                    case 6:
                        $sourcePath = imagerotate($sourcePath, -90, 0);
                        break;
                    case 8:
                        $sourcePath = imagerotate($sourcePath, 90, 0);
                        break;
                }
</code>
Thank you for your help.
Answer: When I see it correctly <code>$sourcePath</code> is a variable to the file path, which can't be rotated...
See http://php.net/manual/en/function.imagerotate.php, you have to pass the opened resourcere of the picture. So you have to do something like this
<code>$oldImage = ImageCreateFromJPEG($sourcePath);
switch($orientation){
    case 3:
        $newImage = imagerotate($oldImage, 180, 0);
        break;
    case 6:
        $newImage = imagerotate($oldImage, -90, 0);
        break;
    case 8:
        $newImage = imagerotate($oldImage, 90, 0);
        break;
    default:
        $newImage = $oldImage;
}
imagejpeg($newImage, $targetPath, 90);
</code>
Comment: Hi Fabian. Thank you for pointing this out. I'm testing this now. So far I can see a small change but now the image is displayed sideways also on iPhone and desktop (earlier it was sideways on desktop but was okay on iPhone). I'm going to try a few things and will update my code. Could you have a look later again? Cheers man
Comment: Nope, you first call `$source = imagecreatefromjpeg($image_temp)` (forget that path in the var name, it will only confuse), it will return a "resource". Then you rotate this resource, so you call `$imageRotated = imagerotate($source, -90, 0);`. In this variable you have the rotated image resource. With `imagejpeg($imageRotated, $targetPath, 90);`, you will write the new image to `$targetPath` (it does not matter when you calculate this). Afterwards, you do not have to move the file, because, you already copied the file via graphicprocessing.

PHP rotated image is blank


Sails.js with a systemd script

Question: I have managed to get a Sails js application working on a server, currently just running with nohup to keep the service running when the SSH session is ended.
Obviously, this is not a very robust solution. What happens if the app crashes or the server is reset etc? I am using Fedora so I am using systemd.
Here is what I have so far.
ExecStart=/usr/bin/node /home/dashboard-app/app.js
Restart=always
StandardOutput=syslog
StandardError=syslog
SyslogIdentifier=dashboard-app
User=***
Group=***
Environment=NODE_ENV=production

[Install]
WantedBy=multi-user.target

The service starts okay but the script does not know about the config files so will default to Sails port 1337. Going to that port on the server will not work either.
I have also got nginx set up to with the port set in the sails config file which works fine but I don't think this will make a difference.
Answer: You need to set WorkingDirectory= to the top-level directory of your Node app, wherever that is.
For example:
[Service]
WorkingDirectory=/home/dashboard-app

or for global-installed apps,
[Service]
WorkingDirectory=/usr/lib/node_modules/dashboard-app

Sails.js with a systemd script


Not able to access vagrant box from host on windows 10

Question: I have a vagrant box setup with below config
<code>  config.vm.hostname = "devops-sk-vm"
  config.ssh.forward_agent = true
  config.ssh.username = "vagrant"
  config.vm.box = "generic/centos8"
</code>
I have a Jenkins running on VM however I am not able to access that from host machine. below are the ports forward and I didn't supply any specific IP. Running Jenkins on 9003.
<code>  for i in 9000..9100
      config.vm.network :forwarded_port, guest: i, host: i
  end
</code>
Box provider: Virtual box
version: 6.1.16
Vagrant version: 2.2.14
Host: Windows 10 Pro 2020
All inputs appreciated.
Answer: I have been able to solve this by checking the firewall service running on generic/centos8. firewalld service runs by default it seems and I had to whitelist the ports to get the traffic in.
Followed this guide to initially disable it and then open the ports.
https://www.digitalocean.com/community/tutorials/how-to-set-up-a-firewall-using-firewalld-on-centos-7


Obj-C circular buffer object, implementing one?

Question: I've been developing for the iPhone for quite some time and I've been wondering if there's any array object that uses circular buffer in Obj-C? Like Java's Stack or List or Queue.
I've been tinkering with the NSMutableArray, testing it's limits... and it seems that after 50k simple objects inside the array - the application is significantly slowed down.
So, is there any better solution other than the NSMutableArray (which becomes very slow with huge amounts of data). If not, can anyone tell me about a way to create such an object (would that involve using chain (node) objects??).
Bottom line: Populating a UITableView from an SQLite DB directly would be smart? As it won't require memory from an array or anything, but just the queries. And SQLite is fast and not memory grinding.
Thank you very much for you time and attention,
~ Natanavra.

From what I've been thinking it seems that going for Quinn's class is the best option possibly.
I have another question - would it be faster or smarter to load everything straight from the SQLite DB instead of creating an object and pushing it into an array?
Thank you in advance,
~ Natanavra.
Answer: Apologies for tooting my own horn, but I implemented a C-based circular buffer in CHDataStructures. (Specifically, check out CHCircularBufferQueue and CHCircularBufferStack.) The project is open source and has benchmarks which demonstrate that a true circular buffer is quite fast when compared to NSMutableArray in the general case, but results will depend on your data and usage, as well as the fact that you're operating on a memory-constrained device (e.g. iPhone). Hope that helps!
Comment: My class implements a dynamically-growing buffer, rather than a fixed-size one, but you could adapt it my removing the resizing code and adding a few changes to release objects before overwriting them. Since I use this to back a queue, and I don't want to overwrite data, I hadn't considered this case. Not a bad idea for a future enhancement...
Comment: Thanks! That sounds like what I'm looking for... although it's not critical, I want to find a way to be able to display 50k-100k of objects easily on a UITableView.
Comment: So does any of CHDataStructures allow to make real FIFO circular buffer, with overwriting previous data upon buffer overfilling? Thanks!
Comment: +1 for a fixed-size circular buffer. That's the use case I generally have for a circular buffer.
Answer: If you're seeing performance issues, measure where your app is spending its time, don't just guess.  Apple provides an excellent set of performance measurement tools.
Comment: I'm sure you think that was a clever gybe on your part, but you're mistaken.  I have a great deal of first-hand experience with people new to Objective-C making guesses as to where their performance issues were.  I spent three and a half years at Apple, including over a year as the sole Cocoa engineer in DTS.
Comment: While parroting Knuth is frequently both safe and impressive to others, there's no guesswork involved when you're talking about shoving multiple tens of thousands of objects into a managed array on a resource-starved embedded system.
Comment: @NSResponder I'm not really new to Obj-C and I don't have any performance Issues. I did test it with instruments and it's not a guess... The problem is with managing a few hundred thousand of objects and displaying them.
I have an SQLite database that helps storing and retrieving everything easily but the question is - how would you display all that mass of data inside a UITableView. So one option would be always retrieving stuff from my SQLite db whenever I want to display something. The other option I thought of was using a circular buffer object.

NSD is right, and your answer is offtopic.
Comment: Nathan, I'm sorry you got canned for your refusal to update your skills, but that's off-topic here.  Those former NeXT employees that you're disparaging rescued Apple from the impending doom that your faction had made nearly inevitable.  I had a great time there for three and a half years, until I left to work on a hardware startup.
Answer: It's trivial to have NSMutable array act like a stack, list, queue etc using the various insertObject:atIndex: and removeObjectAtIndex: methods. You can write your own subclasses if you want to hardwire the behavior.
I doubt the performance problems you are seeing are being caused by NSMutableArray especially if your point of reference is the much, much slower Java. The problem is most likely the iPhone itself. As noted previously, 50,000 objective-c objects is not a trivial amount of data in this context and the iPhone hardware may struggle to managed that much data.
If you need some kind of high performance array for bytes, you could use one of the core foundation arrays or roll your own in plain C and then wrap them in a custom class.
It sounds to me like you need to switch to core data so you don't have to keep all this in memory. Core data will efficiently fetch what you want only when you need it.
Comment: @TechZen: (nitpicking) Objective-C's messaging does not make it slower than just plain C, because you don't need to use it.  Normal function calls are perfectly valid Objective-C, and have the same speed as they would in "normal" C code.  One doesn't need to use the feature just because it's there.
Comment: NSArray is not particularly fast, so while it may not be the sole cause of the performance issue, it's not going to help anything.
Comment: I've never seen Java best a compiled language on the same hardware. As NSD has noted, Objective-C's messaging makes it slower than just plain C (which is part of why you can't use it for drivers) but its still faster than a VM by a lot. I think the OP is unconsciously comparing Java's performance on a non-embedded system to Objective-C's performance on the embedded iPhone and assuming the problem is with the language/API instead of the hardware. If he doesn't have a feel for the speed of the hardware he will waste time looking for bottlenecks that don't exist.
Answer: You can use STL classes in "Objective-C++" - which is a fancy name for Objective-C making use of C++ classes. Just name those source files that use C++ code with a ".mm" extension and you'll get the mixed runtime.
Answer: Objective-C objects are not really "simple," so 50,000 of them is going to be pretty demanding. Write your own in straight C or C++ if you want to avoid the bottlenecks and resource demands of the Objective-C runtime.
A rather lengthy and non-theoretical discussion of the overhead associated with convenience:
http://www.cocoabuilder.com/archive/cocoa/35145-nsarray-overhead-question.html#35128
And some simple math for simple people:

All it takes to make an object as opposed to a struct is a single pointer at the beginning.

Let's say that's true, and let's say we're running on a 32-bit system with 4 byte pointers.
4 bytes x 50,000 objects = 200000 bytes
That's nearly 200MB worth of extra memory that your data suddenly needs just because you used Objective-C. Now compound that with the fact that whatever NSArray you add those objects to is going to double that by keeping its own set of pointers to those objects and you've just chewed up 400MB of RAM just so you could use a couple of convenience wrappers.
Refresh my memory here... Are swap files on hard drives as fast as RAM? How much RAM is there in an iPhone? How many function calls and stack frames does it take to send an object a message? Why isn't IOKit written in Objective-C? How many of Apple's flagship applications that do a lot of DSP use AppKit? Anybody got a copy of otool they can check with? I'm seeing zero here.
Comment: Unless you've profiled and proven that your C solution is faster, I wouldn't do that.
Comment: @NSD: Burden of proof is on the one claiming that there is a slowdown.
Comment: 200000 bytes is 200kB not 200MB - that's quite an important difference.
Comment: You should read that entire thread, including the message from Chris Kane, before you blithely assume that rolling your own linked list implementation is going to outperform NSArray.
Comment: As it happens, an Objective-C object is quite simple.  All it takes to make an object as opposed to a struct is a single pointer at the beginning.  The idea that Obj-C instances are "heavyweight" is a misconception carried over from deliberate misinformation that was tossed around by the C++ die-hards at the time of Apple's transition to OS X.

NSArray is quite efficient for most uses, and it's rather stupid to just write your own container implementation instead of *measuring* to see if NSArray's performance is the bottleneck.
Comment: You'd have to write some pretty terrible code to come up with a C-based linked list implementation that's slower than the amount of Objective-C message passing involved in maintaining an NSArray.
Comment: I did read the entire thread, and I see no reason to question my conviction that an NSArray full of 50,000 NSObjects is going to be slower than just about everything else in the world. If you have evidence to the contrary, then you should post it instead of blithely assuming that your snark alone constitutes something of value.
Comment: Yeah, so about that evidence... Do you actually have any that might prove objc_msgsend isn't a horrible bottleneck that slows everything it touches to a crawl, or are you just going to keep regurgitating the same NeXT employee litany against logic that's been keeping Objective-C from reaching any degree of popularity outside of the cult that birthed it since 1988?
Comment: Chuck,  I think Nathan has certainly proven something, although it wasn't what he intended to prove.  ;-) Nathan, you might want to refresh your memory on the difference between megabytes and kilobytes.  Thanks for the laugh, though.  I think I see why Apple decided to dispense with your services.
Comment: "some simple math for simple people" - well, apparently you cannot follow your own advice because 200000 bytes is NOT 200MB however you look at it.


Magento - Bundle product inside bundle products (Almost working)

Question: I'm trying to add bundle products inside another bundle product.
It's quite simple to achieve my status. Edit the file /app/code/Mage/Bundle/etc/config.xml like this:
                ...
                <allowed_selection_types>
                    <simple/>
                    <bundle/>
                    <virtual/>
                </allowed_selection_types>
                ...

By doing so, you'll be able to successfully create a bundle product with another bundled products inside of it!
My problem is that I can't add this product to an order, via AdminPanel or SOAP (didn't tried trough frontend, but probably doesn't work too).
When I click "Add Selected Product(s) to Order" in the Admin Panel I get the following error:
[19-Jun-2013 15:52:48 UTC] PHP Fatal error:  Call to a member function getPosition() on a non-object in app\code\core\Mage\Bundle\Model\Product\Type.php on line 865

The crash occurs at shakeSelections($a, $b): the code $a->getOption() doesn't returns a object. It's not null and it's also not an object (I'm a PHP noobie, so it doesn't make sense to me).
==Update==
Now I'm able to add this new kind of products into the cart! I've edited the file app\code\core\Mage\Bundle\Model\Product\Type.php, so now I have the following code:
...
/*
 * Create extra attributes that will be converted to product options in order item
* for selection (not for all bundle)
*/
$price = $product->getPriceModel()->getSelectionFinalTotalPrice($product, $selection, 0, $qty);
$attributes = array(
        'price'         => Mage::app()->getStore()->convertPrice($price),
        'qty'           => $qty,
        'option_label'  => is_null($selection->getOption()) ? '' : $selection->getOption()->getTitle(),
        'option_id'     => is_null($selection->getOption()) ? 0 : $selection->getOption()->getId()
);

$type = $selection->getTypeInstance(true);
if (get_class($type) != 'Mage_Bundle_Model_Product_Type'){
    $_result = $selection->getTypeInstance(true)->prepareForCart($buyRequest, $selection);
}
...

and also the function below:
public function shakeSelections($a, $b)
{
    $ta = $a->getOption();
    $tb = $b->getOption();

    $aPosition = array(
            is_null($ta) ? 0 : $ta->getPosition(),
            $a->getOptionId(),
            $a->getPosition(),
            $a->getSelectionId()
    );
    $bPosition = array(
            is_null($tb) ? 0 : $tb->getPosition(),
            $b->getOptionId(),
            $b->getPosition(),
            $b->getSelectionId()
    );
    if ($aPosition == $bPosition) {
        return 0;
    } else {
        return $aPosition < $bPosition ? -1 : 1;
    }
}

I'm investigating to discover possible side effects I've introduced. At this moment I see that there will exist problems with the stock management of this bundle of bundled products.
Please post your updates if your go any further. Thanks a lot!
== Second EDIT ==
I've started this repo at github, so that you can follow my progress and maybe help me somehow.
https://github.com/matheusjadimb/MagentoBundleOfBundled
Comment: When you'll get a task to upgrade your 1.7 to 1.9, you will be having a hard time because your core files are overwritten.
Answer: Just don't do it!
I had a lot of hard times trying to get this working properly. I learned that you should create your own product types instead of editing existing ones.


Negative value for area

Question: I have a problem with the following example:Given the surfaces:$$x^2+y^2+z^2=5, x^2+z^2\ge (y-1)^2$$ find the area bounded with them. First problem appears when I try to sketch this in 3D. For the first one is sphere and that is OK, and the second one should be infinite cone right? (but not sure what part of it left or right, since it is on y axis).
Then for intersection I get $x^2+z^2=1$ and after cilindrical coordinates it is easy to see that $0\le r\le 1$ and $0\le \theta \le 2\pi$.
After that, I am calculating the area of cone and sphere seperatly. So for sphere i get $$\sqrt{5}\int\limits_{0}^{2\pi}d\theta \int\limits_{0}^{1}\frac{rdr}{\sqrt{5-r^2}}$$. But this integral has a negative value, so I am obviously mistaking somewhere but not sure where.
BTW i used that $y=\sqrt{5-x^2-z^2}$ from the equation of sphere and than plugged that into formula.
Comment: The first equation is indeed a sphere, a surface, but the second equation is a "filled / solid cone", not a surface. Which **area** should be computed? Then the integral is definitively done on a positive function, so it is positive. (We cannot know how you obtained a negative value...)
Comment: The area between sphere and cone. So i need to find $P_1$(area of sphere) and $P_2$(area of cone) and to add the together. For integral, my bad.
Comment: Please note you will have two cones from the equation along $y-$axis, with vertex at $(0, 1, 0)$ and increasing radius as go up the $y-$ axis and one inverted cone as you go down the $y-$axis. There are two intersections of the solids, at $y = -1, 2$. Now it is confusing which bounded surface area the question seeks.
Comment: In fact based on the inequality sign it seems it seeks surface area of sphere bound between those two cones.
Comment: I'm not sure what $\ge$ is telling me which cone am I watching etc?
Comment: So is it correct to add the area of sphere and cone?
Comment: If it was seeking surface area bounded between each cone and the sphere, it would have said $x^2 + z^2 \leq (y-1)^2$. $\geq$ means it is outside the cones.
Comment: I get it, and should i correct something now?
Comment: No the surface area that you would see between the cones will only be of the sphere.
Comment: BTW: while your integral is far from the realities of this problem, it has a positive integrand, so how could it ever be negative?
Comment: If the surface area is only sphere, than the final integral is solution right? For the integral my bad, sorry.
Comment: @MilicaKoprivica No it is not correct. Please see the $2$D sketch I added to my answer.
Answer: It is easier to do it in spherical coordinates.
Your integral should be
$\displaystyle \int_0^{2\pi} \int_{cos^{-1}({\frac{2}{\sqrt5}})}^{\pi - cos^{-1}({\frac{1}{\sqrt5}})} 5 \sin \phi \, d\phi \, d\theta$
If you see from top ($z-$ axis) in $XY$ plane, this is how the projection looks. This sketch helps to understand the limits of integral.

EDIT: also given you were doing it in cylindrical coordinates, here is the integral in cylindrical coordinates with the correct limits. Please note $-1 \leq y \leq 2$ so you will have to split the integral into two parts, one for surface area above $XZ$ plane and one for below it. For $y = -1, r = 2 \,$ and for $\, y = 2, r = 1$
For above: $\displaystyle \sqrt{5} \int_{0}^{2\pi} \int_{1}^{\sqrt 5}\frac{r}{\sqrt{5-r^2}} \, dr \, d\theta$
For below: $\displaystyle \sqrt{5} \int_{0}^{2\pi} \int_{2}^{\sqrt 5}\frac{r}{\sqrt{5-r^2}} \, dr \, d\theta$
Comment: We got the same result... thank you for the correction. I've always been quite *clumsy*...
Comment: That is correct. You get upper bound of $r$ for $y = 0$. Yes you add both surface areas. You are basically discarding the surface area that is above  $y = 2$ or below $y = -1$. The reason - for those points on the surface $x^2 + y^2 \leq (y-1)^2$.
Comment: And pls let me know if you have questions.
Comment: $S=6 \sqrt{5} \pi\approx 13.4\%$ of the sphere is too small, looking at he actual plot of the surface
Comment: @Raffaele this is correct. I think you mistook the radius.
Comment: We all have those moments! :)
Comment: Just saw this, sorry. OK, my bad, I also got $y=2, y=-1$ but for some reason i canceled $y=-1$ :). I have questions, first we got upper bound $r=\sqrt{5}$ when we set $y=0$ right? And I add these two volumes at the end right? My main problem is to sketch and read from the picutre :(.
Answer: $x^2+y^2+z^2=5$ and $ x^2+z^2= (y-1)^2$ intersect at
$y^2+(y-1)^2=5\to y_1=-1;\;y_2$
The surface is in the picture below and its area is $S=2\pi rh$.
where $r=\sqrt 5$ is the radius of the sphere, $h$ is the height $h=|y_2-y_1|=|2-(-1)|=3$
Therefore $$S=6\sqrt 5\pi$$
which is $67\%$ of the area of the sphere $20\pi$
Comment: Radius is $\sqrt 5$ and not $5$.
Comment: @MathLover Thank you!

Negative value for area


MUI Change ListItemText styles when active in react-router

Question: I am currently using ListItem from MUI. I am trying to make it bolder when it is active but seems font-weight doesn't work.
See below for the code.
<List
      component='nav'
      aria-label='main mailbox folders'
    >
      <ListItem
        button
        component={NavLink}
        exact
        to='/accounts'
        activeClassName={classes.active}
        className={classes.appBarNavButtons}
      >
        <MyAccountsIcon />
        <ListItemText
          style={{ marginLeft: '20px', fontSize: 'large' }}
          primary='My Accounts'
        />
      </ListItem>
</List>

Style:
appBarNavButtons: {
  color: colors.blueGrey[800],
  textTransform: 'none',
  letterSpacing: 0,
},
active: {
  color: '#0056b3',
  fontWeight: 'bolder',
  '& $icon': {
    color: theme.palette.primary.main,
  }
}

Any help or suggestions will be appreciated.
Answer: V5
In v5, the button prop of ListItem and makeStyles are deprecated. The alternatives are ListItemButton and styled as demonstrated from the example below:
import MuiListItemButton from '@mui/material/ListItemButton';
import ListItemText from '@mui/material/ListItemText';
import { styled } from '@mui/material/styles';

const ListItemButton = styled(MuiListItemButton)({
  '&.active .MuiTypography-root': {
    fontWeight: 'bold',
  },
});

<ListItem disablePadding>
  <ListItemButton component={NavLink} exact to="/">
    <ListItemText primary="Home" />
  </ListItemButton>
</ListItem>

V4
Your styles has lower priority than the one from Typography inside the ListItem, you can override it by using nested selector to increase the CSS specificity:
const useStyles = makeStyles({
  active: {
    '& .MuiTypography-root': {
      fontWeight: 'bold',
    },
  },
});

<ListItem
  button
  component={NavLink}
  exact
  to="/"
  activeClassName={classes.active}
>
  <ListItemText primary="Home" />
</ListItem>

Comment: @Ohhimarccc I've updated my answer. I was using the wrong css selector. Sorry.
Comment: Hey man @NearHuscarl, big thanks for the help. Unfortunately, it still doesn't make the text bolder. I'll try to add .active and see if it works. Thanks again!
Comment: Hey @NearHuscarl, it works! Thank you so much for the big help!


changing column to row with specific columns

Question: i have a json data which can genrate this type of table

but i wand categories data under category name with price range
my required out put like this table
Answer: Using pd.pivot_table() you can do this:
First we need to make the new 'department' 'Total Pages' and add it to the dataframe.
df_tot = df.groupby(['category', 'date'])[['below_1k', 'below_10k', 'below_100k', 'above_100k']].sum().reset_index()
df_tot.loc[:, 'department'] = 'Total Pages'
df = pd.concat([df, df_tot])

Now we can pivot our dataframe.
df_pivot = df.pivot_table(index=['date', 'department'], columns=['category']).T
df_pivot = df_pivot.swaplevel()

Output:
date                   2022-08-22        ... 2022-09-05
department                     CD Other  ...      Other Total Pages
category                                 ...
Colleges    above_100k       59.0  62.0  ...        NaN         NaN
Exam        above_100k        NaN   NaN  ...        8.0        17.0
StudyAbroad above_100k        1.0   1.0  ...        1.0         2.0
Colleges    below_100k       77.0  85.0  ...        NaN         NaN
Exam        below_100k        NaN   NaN  ...       26.0        63.0
StudyAbroad below_100k        4.0   5.0  ...        4.0         8.0
Colleges    below_10k        28.0  31.0  ...        NaN         NaN
Exam        below_10k         NaN   NaN  ...        9.0        20.0
StudyAbroad below_10k        28.0  24.0  ...       23.0        47.0
Colleges    below_1k          0.0   0.0  ...        NaN         NaN
Exam        below_1k          NaN   NaN  ...        0.0         0.0
StudyAbroad below_1k         26.0  24.0  ...       22.0        43.0


FINE logging not logging

Question: log4j.properties
log4j.rootLogger=FINE, stdout

log4j.appender.stdout=org.apache.log4j.ConsoleAppender
log4j.appender.stdout.layout=org.apache.log4j.PatternLayout
log4j.appender.stdout.layout.ConversionPattern=%d{ABSOLUTE} %5p %t %c:%L - %m%n

log4j.category.my.root.package=FINEST

My Class
public class MyClass {
    private static final Logger logger = Logger.getLogger(MyClass.class.getName());

    public boolean download(String destinationPath) {
        HttpURLConnection con = null;
        int i;

        try {
            logger.log(Level.FINE, "Download URL {0}", new Object[] { url.toString()});
        con = (HttpURLConnection) url.openConnection();
        con.setInstanceFollowRedirects(true);

        InputStream is = con.getInputStream();
....

Despite my breakpoint reaching the url.openConnection(); line, the Level.FINE doesn't show up in my console.  Here's the console I do see:
INFO: Order: #298596(Status: 1)
15:00:58,532 DEBUG main org.hibernate.engine.transaction.spi.AbstractTransactionImpl:158 - begin
15:00:58,532 DEBUG main org.hibernate.engine.jdbc.internal.LogicalConnectionImpl:295 - Obtaining JDBC connection
15:00:58,558 DEBUG main org.hibernate.engine.jdbc.internal.LogicalConnectionImpl:301 - Obtained JDBC connection
15:00:58,559 DEBUG main org.hibernate.engine.transaction.internal.jdbc.JdbcTransaction:69 - initial autocommit status: true
15:00:58,559 DEBUG main org.hibernate.engine.transaction.internal.jdbc.JdbcTransaction:71 - disabling autocommit
15:00:58,615 DEBUG main org.hibernate.SQL:104 - MY-QUERY
15:00:58,657 DEBUG main org.hibernate.engine.transaction.spi.AbstractTransactionImpl:173 - committing
15:00:58,661 DEBUG main org.hibernate.engine.transaction.internal.jdbc.JdbcTransaction:113 - committed JDBC Connection
15:00:58,661 DEBUG main org.hibernate.engine.transaction.internal.jdbc.JdbcTransaction:126 - re-enabling autocommit
15:00:58,664 DEBUG main org.hibernate.engine.jdbc.internal.LogicalConnectionImpl:314 - Releasing JDBC connection
15:00:58,664 DEBUG main org.hibernate.engine.jdbc.internal.LogicalConnectionImpl:332 - Released JDBC connection
15:00:58,664 DEBUG main org.hibernate.engine.jdbc.internal.proxy.ConnectionProxyHandler:219 - HHH000163: Logical connection releasing its physical connection
INFO: #298596: Importing...

How come I'm not seeing my own custom logging?
Changing log4j.rootLogger=FINE, stdout to log4j.rootLogger=INFO, stdout does hide all DEBUG from the console, so I know this file is being parsed.
Answer: replace
log4j.rootLogger=FINE, stdout

with
log4j.rootLogger=TRACE, stdout

And check here: http://logging.apache.org/log4j/1.2/apidocs/org/apache/log4j/Level.html
and http://logging.apache.org/log4j/1.2/manual.html
The second link says:
Loggers may be assigned levels. The set of possible levels, that is:

TRACE,
DEBUG,
INFO,
WARN,
ERROR and
FATAL

Answer: The levels for log4j are differents from Java Loggin Framework.
For log4j, all the possible options are:

ALL
TRACE
DEBUG
INFO
WARN
ERROR
FATAL
OFF

FINE logging not logging


Powershell Script Deployed through Intune - Command Not Found

Question: Not sure if this is for stakoverflow or serverfault.
I am deploying a Powershell script using MS Intune. The script works when run locally, but when deployed I get the error below:

Remove-LocalGroupMember : The term 'Remove-LocalGroupMember' is not
  recognized as the name of a cmdlet, function,  script file, or
  operable program. Check the spelling of the name, or if a path was
  included, verify that the path is  correct and try again. At
  C:\Program Files (x86)\Microsoft Intune Management

I am not sure why this commandlet is unavailable as it is definitely there if I open a powershell and run this command.
I am logging the $user variable to check that it is not null or running under a different context.
The code is quite simple as below:
<code>$user = $(whoami)

$user | Out-File 'C:\powershelllog.log'

Remove-LocalGroupMember -Group Administrators -Member $user
</code>
Comment: the module that cmdlet is in was added with ps5.1 and does not exist in 5.0 or earlier. do you have that module on the device in question? this >>> Microsoft.PowerShell.LocalAccounts — https://learn.microsoft.com/en-us/powershell/module/microsoft.powershell.localaccounts/?view=powershell-5.1 <<<
Comment: Yes, on the local computer, I open Powershell and then start typing the command and press tab, then it comes out. I can run the script locally on the computer.
Comment: when you say "local computer" do you mean the one that intune is targeting or the one that you are coding on?. also ... the module may not be in the path that the intune stuff is using. have you tried adding code to verify that the module is visible to intune on that system?
Comment: Intune is deploying a script, it runs under the context of the logged on user. It doesn't work through Intune, if I run it locally as in the same script is saved on the C drive and I run it from there then it works.
Comment: I have set the script to dump the output of get-command to the log file and the weird thing is that it doesn't have the command listed when done from Intune, but it does if I run get-command locally. I need to know why this is? It's not making sense to me.
Comment: so it can be manually run on the target system using the account in question? if so, then you have a truly bizarre glitch and i have not idea how to proceed. [*sigh ...*]
Comment: Looks like I will need to find a different way of removing the group membership. If anyone knows of different commands to look at then please let me know.
Answer: I believe I've run into the same issue as you are having.  I've been trying to create a local admin account on machines.  Running the powershell script with the system context in Intune.  What I've found is that you must check: "Run script in 64 bit PowerShell Host" inside of the Intune where you import powershell scripts.
Apparently not all commands are available with the 32 bit ps console running that way.
I also used the get-command to determine what module the command that was reporting not found was is in, and used the import-module  at the top of my script in case.
Comment: Thanks, I will look for this next time I am logged into Azure. In the end I used WMI embedded within the PS script instead.