Is this plastic pipe connecting city water to the main line dangerous?

Question: I bought a whole house water filter to hook up to the main water line. The plumber who came in said that he won't be able to install it because the pipe that comes from the ground hooked up to the copper pipe is plastic.
He says that this plastic is usually not used for that kind of water pressure for the main line and can burst at any time. If he starts cutting the pipe above it to hook up the water filter, there is a potential that the plastic could break/leak due to all the shaking etc. He has asked me to contact the builder/home inspector (as it shouldn't have passed the home inspection like that? ) and take care of this first.
Picture is below. The black color pipe is the one in question. Has anyone seen plastic pipes come up from the ground like that to the main line? Will it burst?

Update - new pics and details
Close up pictures on request. I looked the pipe closely. It is written 1 1/2" 0.1 / Plastic. (above the first ring at the bottom, you can see it in the second pic).
House is built in 1993.
Comment: (side note) I'm not an expert but-- isn't grounding to those pipes kinda pointless, since it's going into a plastic pipe into the ground?
Comment: I'd be a lot more worried about my ungrounded electrical system than the plumbing.
Comment: Did you read this "*1 1/2" 0.1 / Plastic*" off the coupling (the black piece that joins the two pipes), or the black pipe itself?
Comment: ok, I read it on the coupling then, I couldn't see anything on the pipe itself. I'll try one more time today to check the pipe in detail.
Answer: Though it may seem odd, it is possible the plumber knows what he's talking about.  If this is a Polybutylene pipe, it could indeed be brittle and fail if it's jostled during the installation of the filter.
It's impossible to tell from the picture what type of pipe that is, but based on the plumbers concern I'd guess it is Polybutylene.
Polybutylene
Polybutylene was used in pipes between about 1980-1994/5, and was commonly used as supply line in the 80's.  It was found (in some cases) to react with oxidants in the water supply, which caused the pipe to become brittle and fail. To my knowledge, this type of piping is no longer used. Though if the house was built; or there was supply line work done, during the 80's, it's likely this is Polybutylene pipe.
High Density Polyethylene
Don't confuse Polybutylene pipe with Polyethylene pipe.  High-density polyethylene is commonly used as water supply line today, and is stable and safe to use.
Cross-linked polyethylene
Cross-linked polyethylene (PEX) is not typically used as an underground supply line, as it can sometimes react with minerals in the soil.  Where PEX is used underground, it's typically encased in sand (or other non-reactive materials) to prevent negative reactions. Because of this it's often more expensive to bury PEX, so other materials are used instead.
How can I tell what it is?
The only way to be sure what type of pipe this is, is to look for markings on the pipe itself.  Polybutylene will be marked PB####, Polyethylene will be marked PE####, Cross-linked polyethylene will be marked PEX-x (where x = A, B, or C).
Comment: Now this is a valid point - IF it's Polybutylene, you should immediately invest in replacing the water main, before the line breaks, because its only a matter of time.  (Voice of experience talking here)
Comment: @codernet I'm not a fan of the rubber coupling on a pressure line, but aside from that the pipe itself *should* be alright. Copper is cut using a [pipe cutter](http://www.photo-dictionary.com/photofiles/list/3900/5237pipe_cutter.jpg), so unless you have to pull the pipe away from a wall (or other obstacle) to cut it, there shouldn't be too much vibration involved.
Comment: @Tester101, it is marked as Cresline HD100 PE 3408. Based on your feedback, I guess it is safe? so whatever shaking/disturbance is done on the upper part for filter installation won't affect this pipe?
Answer: Isn't that your water meter on the inside of your house, that the black city line feeds?
Shouldn't the whole house water filter be going AFTER the water meter?
In which case the black pipe is irrelevant, is it not?
Which leads me to think - you need a different plumber.
Comment: Furthermore - looking at the picture more closely, the water meter is connected using a compression fitting, so all your plumber needs to do to install the whole house filter safely is shut off the main, disconnect the compression fitting by unscrewing it, then he can remove the copper from the wall by removing the mounting braces with almost no vibrations at all - and after the pipe is free of the wall he can use a tubing cutter to cut the pipe wherever he needs without shaking it as well...
Comment: Sounds like a plumber who did t want to put a filter in to me... Lol
Comment: he may be afraid of the weight of the meter snaping the pipe and or bumping it etc.
Comment: @Kendrick The meter connects on both ends - the same way too - simple solution there would be disconnect the intake line first.
Comment: What he said is that if he cuts the copper pipe above, it may shake this plastic, and he just does not want to cause any probable damage and cause a leak later. He said he can do it but its not advisable for me.
Comment: which is the compression fitting?
Comment: The two oversized connections at the end of the curved pipes at the water meter.  They each are made up of two halves that screw together with a gasket in the middle.
Answer: Yes, it's common. In fact, nearly all modern residential construction uses plastic PEX piping (and it's widely considered superior to copper).
Now, perhaps your plastic pipe is wrong... but that would be interesting as it's no simple task to replace an entire water main... Can you take a better photo of the plastic pipe?
Comment: Not all *plastic* pipe is PEX.
Comment: I also disagree that nearly all modern construction uses PEX.  While it's popularity is on the rise, many installers still prefer CPVC (rigid, uses lots of connecting fittings) or copper (expensive, tends to get stolen).  PEX is distinctive in that it's a flexible line that requires no elbow joints or connectors every 8' - but its new, so many plumbers are dubious about it (without cause IMO - just dislike change cause, you know, its different...)
Comment: @Tester101 this is true, but I find that *usually* when people say "plastic pipe" in-wall residential they are talking about PEX.
Comment: @TheEvilGreebo PEX isn't new, it's just newer in this area. There was, likewise, a time when some "old-school" builders refused to use plywood. IMHO the resistance to PEX often comes from people who are simply uncomfortable working with it. The point of my post is that it is most definitely not a cause for concern, and **is** quite common and **is not** dangerous.
Comment: It is new, relative to the age of the plumbers out there working with it.  Just got to any big box store and see how much PEX components don't fill the shelves compared to copper and PVC.
Comment: Fair enough, but I attribute that more to the fact that it requires different tools to work with it. People like the system they've used before, too.
Comment: "*it is most definitely not a cause for concern, and **is** quite common and **is not** dangerous.*" Unless the pipe you're saying is PEX is actually Polybutylene, in which case it **could** be cause for concern.
Comment: @Tester101 that's a fair statement... but based on the OP's question about "plastic" pipes, and the plumber not wanting to work on plastic pipes.... and whether or not it's common for plastic pipes to come up from the ground.... He'll just have to look for indicative markings on the pipe.
Answer: That looks very similar to the plastic pipe the brings water into my house.  Depending how much is visible, you may be able to find some writing that will tell you more about it.  Different pipes that look similar may be rated for different PSIs. Ours had a couple of leaks out in the ground and was rated for (iirc) 100psi.  The new pipe that we had put in looked almost identical but was a little thicker and rated for 200psi.
The guys that did my line replacement told me that the older stuff was ok for wells but city psi is much higher and also that in the city, the psi raises at night and other times when there is less demand.
Realistically, I'd get a 2nd opinion.  I don't see any reason why turning the water off and installing a whole house filter would compromise the existing stuff.  Once you turned the water off, you'd disconnect one of the unions going to the plastic pipe, so you aren't going to wiggling on the plastic pipe at all anyway. It may be a legitimate concern, but it might also be that he didn't want to be on the hook for issues that you may have later down the line.  Did it seem like he was trying to convince you to replace the supply line, or just talk you out of installing a filter?
Comment: He said he does not have a problem installing the filter. But   it is possible that we could accidentally damage the set up due to cutting pipe/shaking etc and he does not want to be responsible for any damage. SO it is in my best interest to get that fixed first and then install the filter.
Answer: no way to tell from the picture. if that is sched40/80 rigid plastic pipe like what that white pipe is he may well be right.  most mobile homes and some new instals use a unerground raited pex like pipe that is armored and made to go in the ground. if they put rigid plastic that is likely to get destroyed even by tree roots. you find that out after your first 2k water bill...
Comment: It doesnt look like it it looks more like pe which is even used for underground sewer mains etc judging by the curve in the pipe it isn't ridge like the PVC pressure pipe other wise the fitting would be of a different type as well
Comment: unecs after moving in to my house I have learned to assume nothing. slightly melted and warped pvc giving it the not straight look as shown in the photo, a 45 shell capping the ice maker take off...  Since we dont have identification markings clearly visible who knows.


How to wire ceiling fan motor to supply but light kit to switch?

Question: Situation: Two wire supply source is at overhead box. Two wire runs to single pole wall switch. New ceiling fan with light kit.
I would like the light kit to be controlled like a conventional overhead light, while the fan motor is controlled by the on-board pull switch.
Is it possible to wire the ceiling fan motor to the supply side, while wiring the ceiling fan light to the switch loop? I think I need three wire on the switch side to do this, but not sure. This is an older house, so no common ground to parasitize, either.
Answer: Your wiring should look something like this.

The incoming "hot" connects to the black motor lead of the fan, and the white wire of the switch loop.  This white wire will be marked at both ends, with black tape, marker, or paint.
Connect the neutral from the feed to the neutral of the fan.
Connect the blue light kit wire, to the black wire coming back from the switch.
Connect all grounds.

This will allow the fan motor to always have power, so it will be controlled by the built in pull switch. The light, on the other hand, will be controlled by the wall switch.

Technically, this is no longer a code approved installation, since there's no neutral at the switch.  However, since you're simply installing a lighting fixture, you're not required to bring the wiring up to current code.
Answer: Since the power supply is coming in at the fixture, you can have the fan hot wire connect to the junction between the switch loop hot and the incoming hot, while the switch loop return connects to the light kit hot. The neutrals all connect and grounds all connect.
You don't need any extra wires since you are in existing work (in a brand new setup, you'd need a 3 wire loop to provide neutral at the switch for future smart switch fun and games, but that's not a concern here).
Comment: @bishop -- I'll see about getting to that tonight when I have some time to put one together
Answer: It isn't completely clear from your terminology exactly what you're dealing with, but let me take a stab at an answer.

Your existing wall controls could be a single switch that controls power to whatever is connected inside the fan.  Or it could be two switches, one for the fan and one for the fan light.  Either or both of those could be a variable control (speed for the fan or dimmer for the fan light).  If there are two switches/controls, each should lead to a separate feed inside the fan's ceiling junction box.
Within the wall junction box, all of the neutrals are typically commoned together.  Just the hot wire is normally switched for each function.
The ceiling junction box could have either one or two feeds from the wall switch(es), depending on the wall switch combination.  It also could have an unswitched power cable.  Typically, all of the neutrals in that junction box are commoned together and a single neutral wire feeds the fan (connected internally within the fan to each function).
The fan could have a built-in light control and it could have a built-in fan control.  You don't need to deal with the internal control wiring.  Just think of the fan as a function and the light as a function.  Each function has power fed to it (a hot wire).  You only need to deal with those power connections, which are readily accessible inside the fan.
Inside the fan, the light circuit and the fan circuit could be fed separately from the ceiling box, or they could be joined to a single feed from the ceiling box.
If the fan has built-in controls for both the fan and the light, the feeds to both circuits may be tied together for a single connection to the ceiling box.  This would normally be just a wire nut, so you can separate them and feed them separately.  If you want to control them separately and at least one function (fan or light) will be controlled from the wall, you will need to separate them and feed them separately inside the fan.
If you have redundant controls (the fan has a built-in control and you also have a wall switch for that function), that isn't a problem.  You just use whichever control you want and leave the other in the "on" position.  If you prefer the wall switch, leave the switch on the fan "on".  If it is a pull chain, you can just leave it short so people don't play with it.
If you want to use the fan's pull chain, you have two choices.  You can stick a little guard over the wall switch as a reminder not to switch it there, or you can remove the wall switch and connect the two wires from that switch together with a wire nut (equivalent to the switch being permanently "on").
If you have redundant controls for both the fan and the light, you don't need to handle them the same way.  You can control one from the wall switch and the other from the built-in fan control.
If you have just a single wall switch and you want to use that to control just one function (in your case, the light), this will work only if you have an unswitched power cable in the junction box.  You can run a wire from that hot connection to the fan's other function (the fan in this case), and then control that function from the fan's built-in control.


statement about properties of sequences

Question: I have a simple statement about sequences I have proven. I am asking for help to see if this statement and proof are correct. If statement is correct, is there simpler way proving it? Huge thanks!!!! Here it is:
Statement: ${\{a_n}\}$ is a Cauchy sequence in R. Let $S_K = \{x=d(a_m,a_n)/m,n>K,K\in N\}$. Here $d(\cdot,\cdot)$ is a distance metric. Also $S_{K+1}\subset S_K $.
Prove: if ${\{a_n}\}$ diverges, then $\exists\epsilon>0\ni\forall K[\forall x\in S_K(x\geq\epsilon)]$. In words, if the sequence diverges then all the distances are larger then certain $\epsilon$.
Proof:
(1) By Cauchy criterion: if $\{a_n\}$ diverges then $\exists\epsilon>0\ni \forall K \exists m,n\geq K \implies d(a_m,a_n)\geq\epsilon $. Rewriting this statement in terms of $S_K$: if $\{a_n\}$ diverges then $\exists\epsilon>0\ni \forall K \exists x\in S_K \implies x\geq\epsilon $. It follows then that $\exists\epsilon>0\ni \forall K (\sup S_K \geq\epsilon)$
(2)To prove the main statement we have to show that:
$\forall x \in S_1 \exists V\ni x\geq \sup S_V$.  (aaa)
Take an arbitrary $x\in S_1$, first notice that $\exists U \ni x\in S_U\subset S_1$. There are two ways in which (aaa) is not true. (1) x is smallest element $\implies \bigcap{_{n\in N}}S_n = {\{x\}}$ which is not true since $n\rightarrow\infty $ and intersection should be empty. (2) $\forall S_K(S_K\subset S_U$ and $x\notin S_K)$ has no supremum which contradicts Least Upper Bound property of real numbers. Hence (aaa) is correct and main statement is true.
Comment: There is a basic problem in your question: first you state that your sequence is Cauchy, and than that it diverges.
Answer: The correct assertion is
$$
\{a_n\} \mbox{ diverges if and only if there exists }\varepsilon>0 \mbox{ such that}\sup S_K>\varepsilon \mbox{ for all } K.
$$
Note that since the sequence $\{\sup S_K\}$ is non-increasing and non-negative, $\displaystyle\lim_{K\to\infty}\sup S_K$ always exists. So the assertion to be proven is simply that the sequence is Cauchy if and only if the sequence $\{\sup S_K\}$ is convergent.
To prove this, notice that if $\{a_n\}$ diverges, then there exists $\varepsilon>0$ such that, for every $K\in\mathbb{N}$, there exist $m,n>K$ such that $d(a_m,a_n)>\varepsilon$; in other words, $\sup S_K>\varepsilon$. As $K$ was arbitrary, $\sup S_K\geq\varepsilon$ for all $K$.
Conversely, if $\{a_n\}$ converges, then it is Cauchy. Fix $\varepsilon>0$; then there exists $K$ such that $d(a_n,a_m)<\varepsilon$ for all $n,m>K$; in other words, $\sup S_K<\varepsilon$. As the sequence is monotone, this shows that $\sup S_{K'}<\varepsilon$ for all $K'>K$. That is, $\displaystyle\lim_{K\to\infty}\sup S_K=0$.
Comment: No, that is not the assertion to be proved. The assertion is that if the sequence diverges, then there is $\epsilon>0$ such that **every** pair of terms are at least $\epsilon$ apart. This is obviously false.
Comment: Ah, I totally agree with that. I read "$\sup S_K>\varepsilon$ for all $K$".
Comment: @Martin: thanks a lot for the explanation, one point I cant get my head around, if supSk>ε for all K, doesn't it mean every x in Sk is also > ε, since you can find 'u' such that x>supSu > ε? There must be wrong link in my logic, I cant find it!
Comment: @Leon: it might help you understand if you replace "sup" with "max". In any case, for example $\sup[0,1)=1$; no point in the set is $>1$.
Answer: It's not true that $\bigcap{_{n\in N}}S_n$ should be empty. For instance, every second term might be equal to the previous term; then $0$ would be in all $S_n$.
If I may offer some advice: You may want to focus slightly less on formal logical manipulations and slightly more on developing intuition and checking examples. It's easy to make an error in a formal derivation of this length; that happens to everyone once in a while. However, intuition and examples can help guide your formal work and help you check and correct it when it's gone astray. In the present case, it's easy to see that the statement can't be true because it's easy to come up with counterexamples. Even just a sequence that starts off with a distance of $0$ and then diverges any way it likes is a counterexample. By thinking about examples and tuning your intuition on them, you can avoid such mistakes much more easily than by just trying to ensure that all your formal steps are correct.
Comment: I don't think there are counterexamples to the assertion in the question. You say "even just a sequence that starts off with a distance of 0 and then diverges any way it likes is a counterexample"; for such a sequence, it is true that there exists $\varepsilon>0$ such that, for every $K$, $\sup S_K\geq\varepsilon$.
Comment: @Martin: There certainly are counterexamples, and joriki has correctly described a large class of them. You misread the assertion in the problem.
Comment: @Brian: yes, you are right.
Comment: @Martin:I admit, my love of formalism led me astray :-). Part (2) of the proof is incorrect, more then that, you can easily draw a pictorial representation of the sequence, value of the sequence member vs its count number in the sequence that will disprove the statement! The best you can do is make conclusions about suprema behaviour as you have shown! Thanks!

statement about properties of sequences


Q: Java Scanner.nextLine() from standard input throws NoSuchElementException, but 'enter' wasn't pressed on the keyboard

Question: I'm writing a small PvP game in Java that has a server (host) and a client (second player), that communicate over a pair of sockets.
In case a player wishes to join a pre-established game, I prompt for the IP address of the game's host over the standard input (System.in). In order to do that I use a Scanner instance. When I try to read the next line and feed it into a String constructor, I receive the following exception:
Exception in thread "Thread-0" java.util.NoSuchElementException: No line found
at java.util.Scanner.nextLine(Scanner.java:1540)
at BattleshipServer.run(BattleshipServer.java:45)
at java.lang.Thread.run(Thread.java:745)

this is in spite of the fact that the 'enter' key on the keyboard hasn't been pressed yet.
There is only one previous use of the standard input:
public static void main(String[] args){
    if (args.length != 1)
        printErrorMessageAndExit(USAGE_ERROR_MESSAGE);
    int port = Integer.parseInt(args[0]);
    if (port < 0 || port > 65535)
        printErrorMessageAndExit("Error: invalid port number");
    System.out.println("Do you wish to join or host a game? ");
    Scanner scanner = new Scanner(System.in);
    String selection = scanner.nextLine();
    scanner.close();
    if (!selection.equals("join") && !selection.equals("host"))
        printErrorMessageAndExit("Error: please select 'join' or 'host'");
 .
 .
 .
}

and the second use which causes the error: (error occurs on the third line)
 System.out.println("Please enter host's IP address: ");
 Scanner scanner = new Scanner(System.in);
 String address = scanner.nextLine();
 scanner.close();

I can't seem to find the problem, but I do know that the first read from the standard input clears the buffer, so it is empty in the second call, but it should block until the 'enter' key is pressed again!
Could this be because the first scanner instance is in a static method, while the second instance is in an instance of the same class?
Comment: @Arc676 i rather think it´s because he closes the `PrintStream` associated with `System.in` and not the common `nextLine` after `nextFoo` answer.
Comment: @KevinEsche A _PrintStream_ associated with _System.in_? And I thought System.in is of type InputStream ...
Comment: @Arc676 You should find one that is the same problem and vote to close.
Comment: The best match I've found: http://stackoverflow.com/questions/23621668/java-closing-scanner-and-resource-leak
Comment: Or this one: http://stackoverflow.com/questions/4565854/why-is-scanner-skipping-inputs-from-the-user
Answer: Don't close() the Scanner. When you close the scanner, it closes System.in, so your second scanner has nothing to read.
When using a Scanner on System.in, you should only ever create one, and reuse it.


Finding integration bounds for density of sum of two independent random variables

Question:
Let $X, Y$ be independent random variables, both uniformly distributed over the interval $(0,1)$. That is, $$f_{X}(a)=f_{Y}(a) =  \begin{cases} 1 & \text{if $0 < a <
 1$}
\\ 0 & \text{otherwise} \end{cases}$$
  Find $f_{X+Y}(a)$.

In my probability course, the solution to this problem was given as follows, but figuring out the integrals was very much "by inspection", and for this one, particular problem.
$$
f_{X+Y}(a) =
\begin{cases}
\int_{0}^{a} dy = a & \text{if $0 < a < 1$}
\\\int_{a-1}^{1} dy = 2 - a & \text{if $1 < a < 2$}
\end{cases}$$
It's not so apparent to me how we know these are the correct integration bounds in these two cases. I want a general, straightforward way to figure out exactly which integrals need to be computed for probability problems of this kind. So I read this answer by André Nicolas, which it finally made it clear to me how to start finding $P(X+Y \le a)$:

Another way: (Sketch) We can go after the cdf $F_Z(z)$ of $Z$, and then differentiate. So we need to find $\Pr(Z\le z)$.
For fixed $z$, draw the line with equation $x+y=z$. Draw the
  square $S$ with corners $(0,0)$, $(1,0)$, $(1,1)$, and $(0,1)$.
Then $\Pr(Z\le z)$ is the area of the part $S$ that is "below" the
  line $x+y=z$. That area can be calculated using basic geometry. There
  is a switch in basic shape at $z=1$.

Then by drawing a figure with a square with vertices $(0,0), (0, 1), (1,0), (1,1)$, I come up with the following two integrals:
$$
\small
P(X+Y \le a) = \int_{0}^{1} \left( \int_{0}^{a-y} f(x) \ \mathrm{d} x \right) f(y) \ \mathrm{d}y = \int_{0}^{1} \left( a-y \right )1  \ \mathrm{d}y = a - \frac{1}{2}   \ \ \ \ \  \text{if $0 < a < 1$}
$$
$$
  \small
P(X+Y \le a) = \int_{0}^{1} \left( \int_{1-y}^{a-y} f(x) \ \mathrm{d} x \right) f(y) \ \mathrm{d}y = \int_{0}^{1}  \left( (a-y) - (1 - y) \right )1  \ \mathrm{d}y = \int_{0}^{1} (a - 1)  \ \mathrm{d}y  \ \ \  \text{if $1 < a < 2$}
$$
It appears that I have made a mistake somewhere, since $\frac{d}{\mathrm{d}\ a}\left(F_{X+Y}(a)  \right) =\frac{d}{\mathrm{d}\ a}\left( P(X+Y\le a) \right) = f_{X+Y}(a)$ in neither case gives me the correct answer for $f_{X+Y}(a)$.
Please help me see my mistake; what am I missing?
Answer: This problem is best solved by drawing diagram by plotting the line $x+y=z$ in 'x-y' plane and measuring the area under the line over the rectangle enclosed by $(0,0), (0,1), (1,0)$ and $(1,1)$ [covering $(x+y\leqslant z)$]. This is my recommendation. Alternatively, you may want to use method of convolution while calculating cdf of the sum X+Y exactly the way you have attempted (for details see this).
Looking at your approach I can see the issue in the range of y used in the integral when you try to find $P(X+Y\le a)$ for $0<a<1$. Unfortunately you can't write: $\int_{0}^{1} \left( \int_{0}^{a-y} f(x) \ \mathrm{d} x \right) f(y) \ \mathrm{d}y = \int_{0}^{1} \left( a-y \right )1  \ \mathrm{d}y$, since, when $0<X<a-y$, $0<a-Y<1$; thus, $a-1<Y<a$; but since we are evaluating the cdf for $0\le a\le1$, the range of Y eventually reduces to $0<Y<a$.
Similar sort of issue appears for the case $1\le a\le2$. Basically we just need to be a bit careful about the ranges so that the bounds used are valid ones.


What's the most convenient way to globally set 2 different form themes for app back-end and front-end

Question: So, theming a form in Symfony2 is easy. You create a custom theme file and you add it to your config.yml file to load it. Done.
However, I have 2 different form themes. One for the front-end of the application and one for the back-end of the application.
I went through the documentation (http://symfony.com/doc/2.3/cookbook/form/form_customization.html) but couldn't find a good and easy way to do this.
When I add the theme to the config.yml file, I have the same theme in both front-end and back-end. I could also include the form within each view like this
{% form_theme form 'form_table_layout.html.twig' %}

However, that means I have to do it within each view.
Is there somehow a way to create a separate config file for front-end and back-end? Can I somehow indicate in the base template file which form theme should be used?
Anything else I could do?
Answer: If you use the Symfony2 default directory structure, i.e. you have a single kernel for both the frontend and the backend, you can only (as you mentioned) either set the form theme in each template, or use the same template application-wide by setting it in the config.yml file.
The alternative solution you mentioned, that is creating two base templates, each one setting a "global" form_theme tag would theoretically work. Create a base front-end.html.twig template for all your frontend pages with the following tag:
{% form_theme form 'form-front-end.html.twig' %}

That would work, but you would be forced to have a form variable in each inherited template. You would also not be able to set the theme to multiple forms in the same page.
You could improve the solution by checking if the form variable is defined before styling it:
{% if form is defined %}
  {% form_theme form 'form-front-end.html.twig' %}
{% endif %}

or even better, if you want to be able to passing multiple form to the same template, you could do it by using a forms array:
{% if forms is defined %}
  {% for form in forms %}
    {% form_theme form 'form-front-end.html.twig' %}
  {% endfor %}
{% endif %}

The good thing is that this would not throw any exceptions, even if you don't pass the variable at all, but you have to remember to put any forms to be rendered into the forms array.
Obviously, you would do the same thing for the back-end base template.
There may be better solutions, but in the meanwhile I hope this helps!
Comment: Thanks for your very well written answer. So far, I found these solutions already, but I really was hoping someone had a better one. However, I fear this is the best possible currently :(
Answer: I also faced this problem some times ago, found this post, and followed the way as Andrea Sprega suggested. Recently I came out of a way which can save some repetitive typings.
Warning: This is somewhat "hackish", is probably not the best way, and is not guarantee to work in next framework release. You'll see why when you read below.
Goal: We want to have different default form templates depending on the application "environment" (the most common examples would be "frontend" and "backend). But fundamentally Symfony isn't aware of such "environment". Although it is possible to split the project into different environments and load different configurations, this is definitely an overkill if what we want is just having different form templates.
I think the best way would be an ability to set/override the default form themes in the base template. So we can have form theme A in frontend base template, and form theme B in backend base template. This sounds the best solution to me because as form theme is a "view" stuff, it makes perfect sense to have it changed in the view. However, the problem seems to be that, when the twig (template) code is executed, the form view is already initialized. So it would be too late to change the default form theme there. (I could be wrong here, because I didn't dig deep enough to have 100% confidence)
So I decided to do it another way. It works like this:

First, I made an assumption that all frontend controllers will extend the same base class (e.g. "BaseFrontendController"). Similarly, all backend controllers will extend the same BaseBackendController class. Here's how we distinguish a frontend and backend environment. This is actually the case in my project.
The default twig templates will be added to these base controller classes. It can be done via a method, or an annotation. In this post I'll use a public method.
Before the controller is executed, overwrite the defined default twig templates.
When the form view is initialized, it will use the default twig template defined in the controller.

Here's how it's done:
Firstly, the default form themes defined in your config.yml will be passed to the constructor of \Symfony\Component\Form\AbstractRendererEngine, and is assigned to the local instance $defaultThemes. This field is protected so that it can be used by its derived classes, but there is no setter to change its value.
So, we need to roll our own Symfony\Bridge\Twig\Form\TwigRendererEngine:
namespace AppBundle\Form\Twig;

use Symfony\Bridge\Twig\Form\TwigRendererEngine as BaseTwigRendererEngine;

class TwigRendererEngine extends BaseTwigRendererEngine
{
    /**
     * @param array $defaultThemes
     */
    public function addDefaultThemes($defaultThemes)
    {
        $this->defaultThemes = array_merge($this->defaultThemes, $defaultThemes);
    }
}

This custom renderer engine is plain simple - it just add a new method to append the default themes to the existing one. And this is why I say it's "hackish" - it will no longer work when the internal is changed.
Secondly, define an interface TwigTemplateProvider which is going to be implemented by the base frontend/backend controller classes:
namespace AppBundle\Form\Twig;

interface TwigTemplateProvider
{
    /**
     * @return array|string The form template path
     */
    public function getDefaultFormTwigTemplates();
}

Thirdly, we need a listener which will run when the controller is executed.
<?php

namespace AppBundle\EventListener;

use AppBundle\Form\Twig\TwigRendererEngine;
use AppBundle\Form\Twig\TwigTemplateProvider;
use Symfony\Component\HttpKernel\Event\FilterControllerEvent;

class PerControllerFormTemplateListener
{
    /**
     * @var \Twig_Environment
     */
    private $twig;

    public function __construct(\Twig_Environment $twig)
    {
        $this->twig = $twig;
    }

    public function onKernelController(FilterControllerEvent $event)
    {
        $controller = $event->getController();

        if (!is_array($controller)) {
            return;
        }

        if ($controller[0] instanceof TwigTemplateProvider) {

            /** @var \Symfony\Bridge\Twig\Extension\FormExtension $formExtension */
            $formExtension = $this->twig->getExtension('form');
            $engine = $formExtension->renderer->getEngine();
            if ($engine instanceof TwigRendererEngine) {
                $templates = (array)$controller[0]->getDefaultFormTwigTemplates();
                $engine->addDefaultThemes($templates);
            }
        }
    }
}

The listener will get the form template name (in string or array) supplied by controllers implementing TwigTemplateProvider interface. Then it will add it to the default theme list and pass it to the form renderer engine.
Now, wire them together by adding the followings to your services.yml:
parameters:
    twig.form.engine.class: AppBundle\Form\Twig\TwigRendererEngine

services:
    app.form.per_controller_template_listener:
        class: AppBundle\EventListener\PerControllerFormTemplateListener
        arguments: ["@twig"]
        tags:
            - { name: kernel.event_listener, event: kernel.controller, method: onKernelController }

Here we set the %twig.form.engine.class% parameter to our own implementation, and added our event listener to the stack.
Using it is very simple. For example, in your base frontend controller, implement TwigTemplateProvider and add the following method:
public function getDefaultFormTwigTemplates()
{
    return 'frontend/form_layout.html.twig';
}

Then this layout will be added to the form template stack when your front controller is executed.


Why can I not iterate through the cookies when I perform a request to an url?

Question: I am trying to perform a get request to https://www.footlocker.dk/. I need to obtain the session that is created, when visiting this url.
I perform the request as following:
<code>            string url = "https://www.footlocker.dk/";

            HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
            request.Proxy = null;
            request.CookieContainer = new CookieContainer();

            using (HttpWebResponse response = (HttpWebResponse)request.GetResponse())
            {

                foreach (Cookie cookie in response.Cookies)
                {
                    Console.WriteLine("name=" + cookie.Name);
                    Console.WriteLine("value=" + cookie.Value);
                    Console.WriteLine("path=" + cookie.Path);
                    Console.WriteLine("domain=" + cookie.Discard);

                }
            }
</code>
However it doesnt return me any cookies..
I need these cookies, when I want to go ahead and make a post request afterward, to perform a specific action on this url.
Regards!
Comment: Are you sure those cookies are set by the document http response, and not a javascript XHR call?
Comment: No I am not sure about that :S How can I verify this?
Comment: As an example, use your browser's dev tools to inspect the network calls. You can see which request (a document, XHR, etc) set the cookies.
Answer: Check the response payloads:
You'll see that the call: https://www.footlocker.dk/api/session?timestamp=1611587725706 has a response header like this:
<code>set-cookie: JSESSIONID=orfy8ma22lox1nd8wxdyf8h4e.fzcxwefapipdb018883; Path=/; HTTPOnly
</code>

The https://www.footlocker.dk/ sets no such cookies. Bear in mind that if you go throug the calls, you'll see multiple cookie sets, and you can't be absolutely sure which one you need to make things work, though I believe that you can get the cookie you need just by making the session call.
The final cookie definition looks like this:
Comment: That is awesome, thank you very much.

How would it look like if I wanted to store this response header that is returned, so I can use it in the request i want to make afterwards, if you wouldnt mind :S
Comment: You can store the the cookie locally in variables and add them to the subsequent request. If you want to use it in another context then you might need to store in a persistent option like a database.
Comment: Don't forget to upvote/accept useful answers


Pointwise limit of a sequence of functions when the domain depends on $n$

Question: I am struggling to prove the pointwise limit of a function which has a domain which depends on $n$, specifically $$f_n(x) = \begin{cases} n^2x, \; x \in [0, 1/n]\\
2n - n^2x, \; x \in [1/n, 2/n]\\
0, \; x \in [2/n, 2]
 \end{cases}$$
I can see intuitively that the pointwise limit is the zero function, however the domain dependence on $n$ is confusing me in the proof.
Comment: The domain of all functions is $[0, 2]$, it  does not depend on $n$.
Comment: I understand this, what I mean is that if we look at $x \in (0,1/n]$ for example, then the interval is going to $0$ as $n \to \infty$, but there will always be a point in that interval where the function gets arbitrarily large because of the $n^2$.
Comment: In order to compute $\lim_{n \to \infty} f_n(x)$ you consider a *fixed* $x$ and look what happens for large $n$. Hint: Consider the cases $x= 0$ and $0 < x \le 2$ separately.
Comment: No. If $n > 2/x$ then $f_n(x) = 0$.
Comment: Ok if $x \in (0, 1/n]$, then for small enough $n$ the definition of $f_n(x)$ says that $f_n(x) = n^2 x$, but for $n$ large enough $x$ wont be in $(0,1/n]$ as this gets smaller and smaller, so $x$ will be contained in $[2/n, 2]$. Is this the idea?
Answer: All functions $f_n$ are defined on the same domain $[0, 2]$. But each function is a piecewise-defined function and the subintervals of the piecewise definition depends on $n$.
It is correct (as you said in a comment) that the functions $f_n$ can take arbitrarily large values for large $n$: We have $f_n(1/n) = n$. But this is irrelevant if we consider pointwise convergence.
For pointwise convergence we fix an argument $x \in [0, 2]$ and study the behavior of $f_n(x)$ for $n \to \infty$. Here it is convenient to treat the cases $x = 0$ and $x > 0$ separately.
If $x = 0$ then $f_n(x) = 0$ for all $n$, so
$$
 \lim_{n \to \infty} f_n(0) = 0 \, .
$$
If $0 < x \le 2$ then $f_n(x)$ depends on $n$ in the following way:
$$
f_n(x) = \begin{cases}
 n^2x     & \text{ if } n \le 1/x \, ,\\
2n - n^2x &  \text{ if } 1/x \le n \le 1/x \, , \\
0     &  \text{ if } n \ge 2/x \, .
 \end{cases}
$$
We see that $f_n(x) = 0$ for all sufficiently large $n$, so that
$$
 \lim_{n \to \infty} f_n(x) = 0 \, .
$$
This proves that $\lim_{n \to \infty} f_n(x) = 0$ for all $x \in [0, 2]$, i.e. $f_n$ converges pointwise to the zero function.
As an exercise, I suggest that you prove that the convergence is not uniform.


Differentiability and continuity of a piecewise function.

Question: Consider
$$f(x) = \left\{
\begin{array}{l l}
0 & \quad \text{if $x=0$}\\
\frac{1-\cos 2x}{x} & \quad \text{otherwise}
\end{array} \right.$$
Which of the following is true?
1.$f$ is continuous
2.$f$ is differentiable
3.$f$ is continuously differentiable
Comment: it is continuous and also differentiable and i think it is also continuously differentiable.Is it correct?
Comment: What are your thoughts?
Comment: Yes. How could you prove that?
Comment: $$\begin{align}1-\cos{2x}&=2\sin^2{x}
\\ \lim\limits_{x\rightarrow 0}{\dfrac{1-\cos{2x}}{x}}&=\lim\limits_{x\rightarrow 0}{\dfrac{\sin^2{x}}{x}}=0\end{align}$$
Comment: Continuity is obvious by just using the deffinition and i calculate  derivative of f at 0 which is f'(0)=2 using the deffinition.So it should be continuously differentiable.
Answer:
Yes, and easy to check.
Yes, also easy to check.
Yes also. To see this part:

$f'(0) = \displaystyle \lim_{x \to 0} \dfrac{f(x) - f(0)}{x} = \displaystyle \lim_{x \to 0} \dfrac{1-cos(2x)}{x^2} = \displaystyle \lim_{x \to 0} 2\dfrac{sin^2x}{x^2} = 2$,
and $f'(x) = 4\cdot \dfrac{sin(2x)}{2x} - \dfrac{1-cos(2x)}{x^2}$ for $x \neq 0$.
Using L'hopital rule we can check that $f'(0) = 2 = \displaystyle \lim_{x \to 0} f'(x)$. Thus $f'(x)$ is continuous at $x = 0$, and hence continuously differentiable.
Answer: Now you need to check the continuity at $x=0$. Given $\epsilon \gt 0$, if there exists a $\delta \gt 0$ such that $|x| \lt \delta$ $$\implies |\frac{1-cos2x}{x}|=|\frac{2sin^2x}{x}| \le|\frac{2x^2}{x}|=|2x| \lt 2\delta=\epsilon$$  S0 for $$\delta = \frac{\epsilon}{2}$$ , we have $|f(x)-f(0)| \lt \epsilon$, and hence as per our definiton $f$ is continuos.
For differentiabilty $$\lim_{h\to 0}\frac{1-cos2h}{h^2}=\lim_{h\to 0}\frac{2sin^2h}{h^2}=2$$.
Hence $F$ is differentiable at $x=0$.
From here you can see the (iii) I hope


Javascript - how to add header in CallPrint function

Question: I have javascript function:

and in the button:
onClick="javascript:CallPrint('printarea')"

Now is working and I can print certain part of the page, but I want to add header with logo and some contact information which show only when print the page.
Answer: Use the @media print CSS tag. Essentially create a style which has display:none and in @media print make it visible.
Something like:

You call your javascript as regular and depending on whether the rendition is on the screen or the printer, the CSS will handle the show/hide of the header with logo
Comment: I can't make it work. Add new style media="print" in the page with my css code but don't work.
Comment: This is a good starting point: http://coding.smashingmagazine.com/2011/11/24/how-to-set-up-a-print-style-sheet/
Comment: OMG I try everything include article from the link and others articles and don't work.
Comment: Finaly just put the code in: @media screen { .noprint { display: none; } } and everything is working. Thanks a lot raidenace :)
Comment: There is no greater satisfaction, than when nothing seems to work and suddenly everything comes together, right? :)


How to parse a string with many dates into a List?

Question: I have a string that look like this:
[12-20-2019 11:27:57, 12-20-2019 11:27:58, 12-20-2019 11:27:59] each date is separate by , how can I parse it into a List<DateTime>?
My code is:
string datesListString = JObject.Parse(jsonContent)["datesList"].ToString();
ListDateTime> datesList = new JavaScriptSerializer().Deserialize<List<DateTime>>(datesListString);

DatesListString is a field of a big JSON file that I need to deserialize.
Comment: Where is your code! What have you tried so far?
Comment: You need to first split the string and obtaining a sequence of strings, then you need to map each string to an instance of DateTime by using the DateTime.Parse method (https://learn.microsoft.com/en-us/dotnet/api/system.datetime.parse?view=netframework-4.8#System_DateTime_Parse_System_String_System_IFormatProvider_)
Comment: I have a question about the initial string: does it include square brackets or not ? It is really important to understand the exact string format (I mean whether or not it contains brackets and what is the separator character) in order to being able to split the string and parse the obtained substrings to instances of DateTime
Comment: yes it have brackets
Answer: string yourString = "[12-20-2019 11:27:57, 12-20-2019 11:27:58, 12-20-2019 11:27:59]";
List<DateTime> dates = yourstring
    .Trim('[', ']')
    .Split(new[] { ", " }, StringSplitOptions.None)
    .Select(s => DateTime.ParseExact(s, "MM-dd-yyyy hh:mm:ss", null))
    .ToList();

Comment: cannot convert from 'string' to 'char' on ```.Split(", ")```
Comment: @andreauttini I've updated my answer; the overloaded version including `StringSplitOptions` is needed to split on string rather than char.
Answer: You can do it by combining string.Split method and Select from System.Linq
var dateString = "12-20-2019 11:27:57, 12-20-2019 11:27:58, 12-20-2019 11:27:59";
var result = dateString.Split(',').Select(d => DateTime.Parse(d, CultureInfo.InvariantCulture));

To skip the square braces you can simply use Trim method, like that
var dateString = "[12-20-2019 11:27:57, 12-20-2019 11:27:58, 12-20-2019 11:27:59]".Trim('[', ']');

Answer: You can simply try:
string dateTimes = "12-20-2019 11:27:57, 12-20-2019 11:27:58, 12-20-2019 11:27:59";
string[] splitDateTime = dateTimes.Split(',');
List<DateTime> dates = new List<DateTime>();
foreach (string dateTime in splitDateTime)
{
    DateTime date;
    if (DateTime.TryParseExact(dateTime, "MM-dd-yyyy hh:mm:ss",
                               CultureInfo.InvariantCulture, DateTimeStyles.None, out date))
      dates.Add(date);
}

Answer: You need to split the string first, and then you can use DateTime.Parse(str) to get the DateTime object.
This demonstrates it:
using System;

public class Program
{
    public static void Main()
    {
        string str = "[12-20-2019 11:27:57, 12-20-2019 11:27:58, 12-20-2019 11:27:59]";
        str = str.Substring(1, str.Length - 2);
        string[] parts = str.Split(',');

        foreach(var part in parts) {
            str = str.Trim();
            var date = DateTime.Parse(part);
            Console.WriteLine(date);
        }
    }
}

Comment: Be careful with DateTime.Parse, never never use it without culture or format!
Answer: It looks like it is JSON:
var _str = @"[""12-20-2019 11:27:57"", ""12-20-2019 11:27:58"", ""12-20-2019   11:27:59""]";

So we can use using Newtonsoft.Json;:
using Newtonsoft.Json;

var list = JsonConvert.DeserializeObject<List<string>>(_str)
    .Select(s => DateTime.Parse(s, CultureInfo.InvariantCulture));

Read mode about library Json.NET


RecyclerView in setReverseLayout scroll to top (or bottom)

Question: Apologies for the potentially misleading title but I had no idea how to word it. If anyone else thinks they can come up with something better please feel free to edit.
I have a RecyclerView which I populate with Firebase records. To make the most recent records show at the top of the list, I have set my RecvlerView to setReverseLayout(true) and setStackFromEnd(true) as suggested here. This works great when the number of items fit within the screen space - the rest of the items smoothly scroll down, giving space for the new item which fades in, as shown below.

The problem is when the existing items take up all of the screen space, the new item is added 'above' the others and the RecyclerView effectively expands above the top of the screen, so to see the new item I need to pull or scroll the list down manually. Another GIF below;

How can I overcome this?
Comment: can you share this example link... this is very useful
Comment: @GunduBandagar sorry, what link do you want sharing?
Comment: you making above code, i want this boss.. :)
Answer: final int SCROLLING_UP = -1;
boolean scrollToNewTop = !recyclerView.canScrollVertically(SCROLLING_UP);
//TODO update adapter here
adapter.notifyItemInserted(adapter.getItemCount() - 1);
if (scrollToNewTop) {
    recyclerView.scrollToPosition(adapter.getItemCount() - 1);
}

This will scroll you up if you are at the very top and leave everything as it is if you're somewhere in a middle saving from annoying jumping.
Answer: this may help:
adapter.notifyItemInserted(position);
recyclerView.scrollToPosition(position);

Answer:   mAdapter.registerAdapterDataObserver(new RecyclerView.AdapterDataObserver() {
        @Override
        public void onItemRangeInserted(int positionStart, int itemCount) {
            super.onItemRangeInserted(positionStart, itemCount);
            int testimonycount = mAdapter.getItemCount();
            int lastVisiblePosition =
                    linearLayoutManager.findLastCompletelyVisibleItemPosition();
            // If the recycler view is initially being loaded or the
            // user is at the bottom of the list, scroll to the bottom
            // of the list to show the newly added message.
            if (lastVisiblePosition == -1 ||
                    (positionStart >= (testimonycount - 1) &&
                            lastVisiblePosition == (positionStart - 1))) {
                recipeRecyclerview.scrollToPosition(positionStart);
            }
        }

Comment: Welcome to Stackoverflow. Its best to add some description to your answer to show how your proposed code solves the problem.


Looking to leave XP SP3 IE8 for Ubuntu

Question: I am a newbie, so I don't know what results I if any I will get. I have been checking out Ubuntu 9 or some number like that on a flash drive, and it seems like open source software and Ubuntu is the way to go.
A tablet looks like the place I would like to jump in. You know, new OS, new device, new day... It's a new wave, so what should I try?

Should I go ahead and buy a low-priced tablet and what specs do I look for?
Should get a Quad core with the most gigabytes?

Maybe an iView 7-inch Android Multi-touch Tablet or something from China? I think that going for a lower end brand tablet and not spending a lot is worth trying until the learning curve tells me it's time for something else.
Comment: This question appears to be off-topic because it is about hardware recommendation.
Comment: Welcome to Ask Ubuntu. Hardware (including tablets) recommendations are off topic here. Please ask one question at a time. Consider installing and learning to use Ubuntu (Xubuntu or Lubuntu) in your XP computer first.
Comment: Seems you are more after a discussion, recommendations and opinions rather than a 'correct' answer. I would suggest you try out a forum such as http://ubuntuforums.org/
Comment: Shopping recommendations are offtopic in most, if not all, Stack Exchange network.
Comment: Yep, http://UbuntuForums.Org is good for the hardware discussions.
Answer: Suggest you start small and simple; create a LiveUSB by downloading Xubuntu's ISO file  - and choose the 32-bit version of the newest release, 13.10. Xubuntu is the version of Ubuntu Linux which looks the most like Windows XP, so we're keeping the learning curve as flat as possible.
Then, once the ISO completes its download, download and use the free Windows program which makes any USB flashdrive into a LiveUSB you can boot from.
Then, reboot your computer and tell it to boot from the LiveUSB, which will allow you to start using Ubuntu Linux without getting a new machine. That way, you can get started today!

Looking to leave XP SP3 IE8 for Ubuntu


MySQL - Are memory table queries slowing down other queries

Question: I'm planning to limit "main tables" (innodb) queries from requests by putting some limitation by ip per minute. My idea is to create mysql table which contains ip, datetime and request type. The problem is when somebody will try brute force and limiting table will block his actions. Will massive ammount of queries to memory table kill the rest of the queries in innodb tables?
If yes, how can I maximize the capacity of main database having the possibility to limit request of certain type from certain ip certain times per minute?
Comment: No, it's not.  Count the number of retries on the middle tier and deny access when you hit the limit.  That's entirely different from the overly complex solution you've proposed.
Comment: "per minute" seems slow to me. MySQL is capable of faster throughput.  What makes you think this design is necessary?  I'll bet your idea of "massive" isn't a problem for a properly designed and indexed schema.
Comment: @duffymo I want to limit some actions in order to prevent brute forcing login (10 tries per minute), spamming register (1 time per hour), or requesting some data too often with some complex queries (everything by ip).
Comment: That should not be done by the database; your middle tier needs to enforce it.  I still say that you're underestimating the database and the query optimizer.  I would not take such a step until measured responses told me it was necessary.
Comment: @duffymo You've got some right, but still I need to prevent bruteforcing login or spamming register. Even ignoring the performance, it's security issue.
Answer:
Will massive ammount of queries to memory table kill the rest of the
  queries in innodb tables?

No! It will not kill the queries for sure. But you should keep in mind few things.
Memory table will grow as new data come in and it will grab the space in system RAM.
This will not harm your innodb as bufferpool is allocated as mysql starts
This will be harful if system reaches to max memory due to growth of your memory table (consumed all ram)! and then you're going to see mysql getting killed by kernel mentioning "out of memory" error.

If yes, how can I maximize the capacity of main database having the
  possibility to limit request of certain type from certain ip per
  minute?

As such the answer is NO but still you can create your user with restricted use of resources.
Review this link to create user with such limitations.
Comment: Great answer! Thank you very much. Consider adding some information how can I limit the size of table and remove old rows by some key to make place for a new ones. Should I use triggers before Insert?


How to configure JBoss 6 with custom auth-method

Question: Perhaps I could ask you if you guys if you could help me out how to configure JBoss 6 with a custom auth-method?
We are moving from JBoss 5 to JBoss 6.
In 5 we got a web.xml with this login-tag
<login-config>
<auth-method>OURSSO</auth-method>
<realm-name>oursso</realm-name>
</login-config>

And a jboss-app.xml
<security-domain>oursso</security-domain>

And in login-config.xml
<application-policy name="oursso">
<authentication>
<login-module code="org.jboss.security.auth.spi.UsersRolesLoginModule" flag="sufficient">
<module-option name="usersProperties">props/mycomp-users.properties</module-option>
<module-option name="rolesProperties">props/mycomp-roles.properties</module-option>
<module-option name="unauthenticatedIdentity">anonymous</module-option>
</login-module>
<login-module code="rsa.ps.ct.jboss.jaas.OURSSOServerLoginModule" flag="required">
<module-option name="connectionProvider">rsa.access.manager:type=Service,name=RuntimeAPIClient</module-option>
</login-module>
<login-module code="org.jboss.security.auth.spi.RoleMappingLoginModule" flag="optional">
<module-option name="rolesProperties">props/mycomp-rolemapping-roles.properties</module-option>
<module-option name="replaceRole">true</module-option>
</login-module>
</authentication>
</application-policy>

And in war-deployers-jboss-beans.xml
<property name="authenticators">
<map class="java.util.Properties" keyClass="java.lang.String" valueClass="java.lang.String">
<entry>
<key>BASIC</key>
<value>org.apache.catalina.authenticator.BasicAuthenticator</value>
</entry>

...

<entry>
<key>OURSSO</key>
<value>com.mycomp.OurssoAuthenticator</value>
</entry>
</map>
</property>

It seems like the auth-method in web.xml must match a key in war-deployers-jboss-beans.xml. How is the same accomplish in JBoss 6?
Best regards
Fredrik
Comment: Any progress in this? I'm also interested..
Comment: Hello, not yet acctually. But I have got some advise from a friend a couple of weeks ago, that I hope I will get time to try out asap. Unfortenately we, our complete team, had to switch focus and fix some issue. Best regards and merry christmas.
Answer: I added these to my standalone-full.xml
<security-domain name="my-security-domain" cache-type="default">
    <authentication>
        <login-module code="org.jboss.security.auth.spi.UsersRolesLoginModule" flag="required">
            <module-option name="usersProperties" value="file://${jboss.server.config.dir}/users.properties"/>
            <module-option name="rolesProperties" value="file://${jboss.server.config.dir}/roles.properties"/>
        </login-module>
    </authentication>
</security-domain>

In the file users.properties
123=qwe
456=asd

In the file roles.properties
123=role.A,role.B
456=role.B

In one of my beans in the server I annotate it with
@Stateless

@SecurityDomain("my-security-domain")
@RolesAllowed("role.A")
public class SecureStatelessBean extends SecureReturnAString implements SecureStatelessBeanLocal, SecureStatelessBeanRemote
{
 ...

In my web-application (running in the same server) I lookup the bean and login with this code
@EJB(lookup = "java:global/ejbtest-app/ejbtest-server-0.0.1-SNAPSHOT/SecureStatelessBean!se.albinoni.ejbtest.stateless.SecureStatelessBeanRemote")
private SecureStatelessBeanRemote secureStatelessBeanRemote;

...

private static SecurityClient getClientLogin() throws Exception
{
    final SecurityClient client = SecurityClientFactory.getSecurityClient();
    client.setSimple("123", "qwe");
    return client;
}

...

SecurityClient client = getClientLogin();
client.login();

secureStatelessBeanRemote.someMethod();

Think that was it.
But I still have not found out how to do the same from a remote standalone app.


Android setBackgroundResource doesn't use image depend on dpi

Question: I wan't to use the setBackgroundResource method to set an image to a button.
I have different folders with the same button in different dpi's but when I set the button from code it uses the drawable folder instead of the correct folder
resume.setBackgroundResource(R.drawable.resumegrey);

the resumegrey is copied in the right folders with diffrent dpi's
Comment: I bet that is an emulator issue. Try on a real device.
Comment: no on real devices to
Answer: DisplayMetrics metrics = new DisplayMetrics();
getWindowManager().getDefaultDisplay().getMetrics(metrics);
float density = metrics.density;

density is float and its value changed as per screen size...
so,if you have
240*320 density is 0.5
320*480 density is 1.0
480*800 density is 1.5

and set size using density like , img.setMaxHeight(density*100);
and also put multiple screen supports in manifest file.Multiple Screen Support
Comment: hmm don't think this helps me, see when u define different folders with hpdi, ldpi and so on it automatically takes the right buttons, but when i set the button with code it uses for every screen the same button


Power build and play strategy in mass effect 3 - Radius/Range vs Damage?

Question: As I've got more into the Mass Effect 3 multiplayer and experimented with various different characters and powers I've noticed that many powers evolution trees often include choices between damage and radius/range.
Grenades are a good example of this but also lots of the biotic and tech powers such as Overload, Incinerate, Carnage, Warp etc.
Personally I've mostly tended to go with damage upgrades over radius but I'm wondering if that is a little short sighted.  Are there certain power builds where it would be better to go for radius?
Can anyone describe some good power builds and play strategies they've used where favoring radius/range is more useful than favoring pure damage?
Answer: Going with damage vs radius depends highly on what you intend to do with the power.  If you are a power spammer you may want to rely on a bread/butter high damaging power to spam so you maintain usefulness against those high tier units such as atlas, banshees, geth primes, etc.  Example powers I like to choose for more damage:

Warp
Incinerate
Carnage

If you prefer to be a support or use your powers to augment your weapons, you may want to use high radius for crowd control.  For example:

Overload (I love to use it for the stun effect)
Cryo Blast
Stasis Bubble (almost a no brainer for stasis)

Just to add a little tidbit from the overload page on the wiki to show its awesomeness:

Overload is highly effective in Mass Effect 3's multiplayer as a crowd control power when fully upgraded along the Chain Overload/Neural Shock path. Place yourself at the entrance to a room enemies are charging through and spam it on the first one to appear.
Comment: Yes I do like Overload, I currently have a Turian Sentinel built with partial chain overload but kinda wish I'd built with full chain overload/neural shock
Comment: @RobV that's the best part about multiplayer, either you'll get respec packs or you can just promote him once he's at level 20 and start over.
Comment: He's already level 20 and I have respec packs, just don't want to promote or respec right now


Hide File on localhost of XAMPP server

Question: I have created a project in PHP and placed it inside htdocs in XAMPP server.
I want to give the project to my friend to run that project locally on his machine to test it .
I don't want him to access the folders and directories I just want him to use the project what is shown in the browser. I want neither he can see my code nor access the files locally.He just can test the functionality in the project.
Is there any way or any tool to do that. Thanks
I use a third-party tool to lock that folder then I cannot access the file from the browser?.
thanks
Comment: well, you must have a foundation to know, that php is using interpreter, it's open source for any user on that PC/NB and in my opinion just activate your ip become public, please take a look in htaccess apache configuration.
Comment: You could obfuscate the source. It won't prevent reverse engineering however. It will make an uninterested person not bother. Option 2, you could clone the rendered results (browser level), and give him that. Option 3, you could fire him now since you dont trust him.
Comment: This makes no sense, this is not how the platform of a web application works. Instead you should publish your application using a http server you yourself control. So that your "friend" (I guess that reads your paying customer?) can access the server only via http protocol, so the way you want things to be.
Answer: You can always use ngrok (https://ngrok.com/) and serve the app from your local host to the internet. You control when it's available, nobody can access the source code and you don't need a real domain or subdomain to do it.
Comment: Well then, I'm afraid you cannot do that without transferring the full source code. Even if it's not accessible from XAMPP itself (Apache to be more accurate), nothing would stop him to just open the folder and have a look at the files.
Comment: I can not do that but the requirement is that I need to transfer the code to his machine and ask him to check all the changes locally I just can't access the internet

Hide File on localhost of XAMPP server


Why is my data frame loaded with blank values when reading XML using spark.xml? (Python/Databricks)

Question: I am reading an XML file using spark.xml in Python and ran into a seemingly very specific problem.
I was able to narrow to down the part of the XML that is producing the problem, but not why it is happening.
Here is the code to read in the XML file:
src = sqlContext.read.format("com.databricks.spark.xml").options(rowTag="root").load("file.xml")

Here is the schema read in from the XML using the spark.xml library, with rowTag = "root":
    root
 |-- AID: long (nullable = true)
 |-- RID: long (nullable = true)
 |-- XmlData: struct (nullable = true)
 |    |-- NC: struct (nullable = true)
 |    |    |-- RS: struct (nullable = true)
 |    |    |    |-- RD: struct (nullable = true)
 |    |    |    |    |-- CR: struct (nullable = true)
 |    |    |    |    |    |-- Addr1: string (nullable = true)
 |    |    |    |    |    |-- Addr2: string (nullable = true)
 |    |    |    |    |    |-- City: string (nullable = true)
 |    |    |    |    |    |-- InFile: string (nullable = true)
 |    |    |    |    |    |-- Name: string (nullable = true)
 |    |    |    |    |    |-- Phone: long (nullable = true)
 |    |    |    |    |    |-- State: string (nullable = true)
 |    |    |    |    |    |-- Zip: long (nullable = true)
 |    |    |    |    |-- SC: struct (nullable = true)
 |    |    |    |    |    |-- Class: string (nullable = true)
 |    |    |    |    |    |-- ClassType: string (nullable = true)
 |    |    |    |    |    |-- Message: string (nullable = true)
 |    |    |    |    |    |-- SC: long (nullable = true)
 |    |    |    |    |-- NC: long (nullable = true)
 |    |    |    |    |-- CRR: string (nullable = true)
 |    |    |    |    |-- RM: struct (nullable = true)
 |    |    |    |    |    |-- Addr1: string (nullable = true)
 |    |    |    |    |    |-- City: string (nullable = true)
 |    |    |    |    |    |-- MemberNo: string (nullable = true)
 |    |    |    |    |    |-- Name: string (nullable = true)
 |    |    |    |    |    |-- State: string (nullable = true)
 |    |    |    |    |    |-- Zip: long (nullable = true)
 |    |    |    |    |-- TL: array (nullable = true)
 |    |    |    |    |    |-- element: struct (containsNull = true)
 |    |    |    |    |    |    |-- _AvgDays: long (nullable = true)
 |    |    |    |    |    |    |-- _Comment: string (nullable = true)
 |    |    |    |    |    |    |-- _Current: long (nullable = true)
 |    |    |    |    |    |    |-- _HC: long (nullable = true)
 |    |    |    |    |    |    |-- _IndType: string (nullable = true)
 |    |    |    |    |    |    |-- _LS: long (nullable = true)
 |    |    |    |    |    |    |-- _OpenDate: long (nullable = true)
 |    |    |    |    |    |    |-- _PD120Day: long (nullable = true)
 |    |    |    |    |    |    |-- _PD30Day: long (nullable = true)
 |    |    |    |    |    |    |-- _PD60Day: long (nullable = true)
 |    |    |    |    |    |    |-- _PD90Day: long (nullable = true)
 |    |    |    |    |    |    |-- _Region: string (nullable = true)
 |    |    |    |    |    |    |-- _ReportDate: string (nullable = true)
 |    |    |    |    |    |    |-- _SourceID: long (nullable = true)
 |    |    |    |    |    |    |-- _TD: long (nullable = true)
 |    |    |    |    |    |    |-- _VALUE: string (nullable = true)
 |    |    |    |    |-- Trends: array (nullable = true)
 |    |    |    |    |    |-- element: struct (containsNull = true)
 |    |    |    |    |    |    |-- _CurrentPct: double (nullable = true)
 |    |    |    |    |    |    |-- _LineCnt: long (nullable = true)
 |    |    |    |    |    |    |-- _PD120DayPct: double (nullable = true)
 |    |    |    |    |    |    |-- _PD30DayPct: double (nullable = true)
 |    |    |    |    |    |    |-- _PD60DayPct: double (nullable = true)
 |    |    |    |    |    |    |-- _PD90DayPct: double (nullable = true)
 |    |    |    |    |    |    |-- _PD: string (nullable = true)
 |    |    |    |    |    |    |-- _TD: long (nullable = true)
 |    |    |    |    |    |    |-- _VALUE: string (nullable = true)

There is more to this schema, but for some reason the XML parser does not get past this point.
I am thinking there is an issue with the 'Trends' tag in the XML, but I cannot find it.
Here is a sample of a 'Trends' tag entry:
<Trends PD="4205" LineCnt="0" TD="0" CurrentPct="0" PD30DayPct="0" PD60DayPct="0" PD90DayPct="0" PD120DayPct="0" />

I understand that a closed tag such as this one could not be read in previous versions of the XML parser, but it works fine while using it in Databricks, and my other files with closed tags are read properly.
Here is the final result to further exemplify what I am explaining (I have 13 records in my XML):
+---------+--------+-------+
|AID      |RID     |XmlData|
+---------+--------+-------+
|     null|    null|   null|
|     null|    null|   null|
|     null|    null|   null|
|     null|    null|   null|
|     null|    null|   null|
|     null|    null|   null|
|     null|    null|   null|
|     null|    null|   null|
|     null|    null|   null|
|     null|    null|   null|
|     null|    null|   null|
|     null|    null|   null|
|     null|    null|   null|
|     null|    null|   null|
+---------+--------+-------+

(This top level view is fine - my code later iterates through the structs/arrays in 'XMLData' - but this needs to be populated first of course)
Does anyone know why this would cause the schema to stop being loaded to completion when parsing?
Please note that I cannot explicitly define a schema.  That would defeat the purpose of the project that I am working on - I must be able to infer the schema dynamically.  Which, again, works fine for other files I am using.
Comment: Did you find the solution for this issue? I am also having same issue here. I was able to find the cause but not sure how to resolve it. The issue here is with inconsistency in values of the Array type field. LEts say, one attribute in one of the array type field has some value = "123" and the same attribute has value="", then you will see all rows of your dataframe as null. I verified it at my end with multiple use case like this. I am sure your xml is also having similar kind of inconsistency in data. Please let me know.
Answer: Cause:
So I was able to figure out why was this happening. You are likely to see this issue when the xml you are trying to convert to dataframe have inconsistent values. For example, something like below will have this issue:
<?xml version="1.0"?>
<Company>
  <Employee id="1">
      <Email>email@example.com</Email>
      <Measures id="id32" type="AttributesInContext">
<Dimensions value="7in" title="Height"></Dimensions>
<Dimensions value="" title="Weight"></Dimensions></Measures>
  </Employee>
  <Employee id="2">
      <Email>email@example.com</Email>
      <Measures id="id33" type="AttributesInContext">
<Dimensions value="6in" title="Height"></Dimensions>
<Dimensions value="" title="Weight"></Dimensions></Measures>
  </Employee>
  <Employee id="3">
      <Email>firstname.lastname@example.com</Email>
      <Measures id="id34" type="AttributesInContext">
<Dimensions value="4in" title="Height"></Dimensions>
<Dimensions value="" title="Weight"></Dimensions></Measures>
  </Employee>
</Company>

Here, since you have value="" in each of the rowTag entry, we will likely to get null in the dataframe for all rows as it is not able to infer the data type. However, if you replace all value="" fields with some actual value, you will see that this issue do not occur.
Solution:
As per databricks link, this issue can be resolved by using option("nullValue", "") option while reading the xml file. So your command will look like this (I tried this in scala, should be similar in python):
var xmldf = sparkSession.read.format("com.databricks.spark.xml")
        .option("rowTag", rootTag).option("nullValue", "").load("/path/to/xml")

Comment: Thanks!  I had a complicated string-replace work-around, I'm glad there is a simpler option.  Much appreciated.


Tub overflow drain upstairs with water damage on downstairs living room ceiling

Question: A couple of weeks ago, I had a large amount of water drain via the overflow drain in my master bath upstairs (the water was too cold so I was draining water not only through the tub's main drain but water was also draining via the overflow drain while I was running additional water to warm the overall temperature).
Over the weekend, I noticed an obvious water damage patch on my living room ceiling directly under the tub. Now, I'm scared to use that bathtub and I'm looking for reassurance that it was likely the "cold water warm up" fiasco that caused the damage.
Hiring a plumber is not really a financially feasible option for me right now.  Thanks for any input.
Comment: Can you take the overflow cover off and see if there is a gasket or if it is connected properly?  Do you have access to the wall behind the tubs drain/valve or  a ceiling under the tub
Comment: Yes, I will take the overflow cover off and see - thank you for that.  I don't have access to the wall behind the tub - it's one of those "inserts" with a vinyl/plastic wall that goes up almost to the ceiling.  The tub is fairly flush to the floor, I have no idea how anyone would be able to gain access underneath the tub.  I'm signing off now (leaving the office) but I'll check back tomorrow.  Thanks so much.
Comment: I mean the other side of the wall.
Comment: I do not know if this is the answer to your problem so it is a comment for now.  Replacing a tub overflow gasket  https://www.youtube.com/watch?v=spCeKSwd_No
Comment: Thanks so much for your help - Alaska Man.  I did check overflow valve gasket and everything seems to be in place. The other side of the wall morphs into the townhome next to mine, if needed I guess someone could gain access through the attic.  Thanks for the visuals and the video, I'll check it out.
Answer: here's a typical tube/over flow drain set up:

The black ring at the top of the picture is a rubber gasket. It forms a seal between the over flow drain pipe and the wall of your tub. If the tubs' drain or stopper needed maintenance the lever would be removed. This may have caused the rubber gasket to become awry. It's tricky to keep it in place while securing the screws that hold the cover.
That is the most likely location of your leak. To repair you must remove the two plate screws and verify the gasket is not split or damaged and centered in the opening. Further the pipe behind it must also be precisely centered to the opening and gasket. Start one screw first turning it until it stays in place. Tighten the next one snugly and finish tightening the first too.
Comment: I agree and sometimes the gasket falls on the ground. Unless there is an access panel a new seal will be needed as long as the tub is not filled to the over flow level it will probably be ok to use.


Rails 4 - Timer (jQuery.Countdown)

Question: I'm trying to create a timer into my Rails. But I'm getting this error:
jquery.countdown.min.self-6add0e5….js?body=1:7 Uncaught TypeError: Cannot read property 'createPlugin' of undefined

I add :

jquery.countdown.min.js into assets/javascripts
jquery.coundown.css into assets/stylesheets
jQuery.js is there and working properly
Into application.js - //= require jquery.countdown.min
Into application.scss - *= require jquery.countdown

Then i create:
VIEW
<th width="20%" class="timeRem" data-countdown-until="<%= 10.days.from_now %>">

timer.js.coffee
 Timers =
  init: ->
    @initCountdownUntil()
    @initCountdownSince()

  initCountdownUntil: ->
    $('[data-countdown-until]').each (index, element) ->
      $element = $(element)
      date = new Date($element.data('countdown-until'))
      $element.countdown(until: date)

  initCountdownSince: ->
    $('[data-countdown-since]').each (index, element) ->
      $element = $(element)
      date = new Date($element.data('countdown-since'))
      $element.countdown(since: date)

window.Timers = Timers

Don't rally know how to fix it, appreciate any advice and help with that.
Comment: Added it as an answer for future Googlers.
Comment: Does `jquery.countdown.min.js` appears after `jquery.min.js` in your rendered page?
Comment: Yeah, i solved it by ordering plugin js first and countdown second..
Answer: You place the scripts on the page in this order jquery.js then jquery.plugin.js then jquery.countdown.js
[
ref: http://keith-wood.name/countdown.html
Answer: As per our comments, jquery.countdown.min.js file should be placed before jquery.min.js.

Rails 4 - Timer (jQuery.Countdown)


Wifi signal antenna

Question: Is there any powerful antenna, set on two storey house height to receive wifi signals from provider?
Is it possible at all to receive wifi signals by hacking it (not from neighbour or around,but signal wave)  or is there any free access source?
Comment: Websearch "cantenna"  for DIY directional wifi  antenna designs.
Comment: Hello, and welcome to Home Improvement Stack Exchange. This isn't really about "home improvement", and is a bit unclear to boot. Unfortunately, there really isn't a good Stack Exchange site for a question like this; you might try [Googling](https://www.google.com/search?q=how+do+i+get+wifi+in+my+house).
Comment: It is related to home somewhat. Well I could not find better place to ask. Thanks to @Richard Crowley I transferred it to EE.
Answer: If your provider offers wireless service (WiMax, 4G, LTE, etc.) then there are external, directional antennas that will extend service to marginal areas. You will need to research exactly what frequency band they are using.
But as Hobbes says, it is not typically "WiFi" as that is meant for LOCAL service inside a home or business.  Unless you are "pirating" WiFi from your neighbors or the coffee shop down the road.
But this question is probably better over in "Electrical Engineering" than here in "Home Improvement".  Perhaps the moderators could consider moving it.
Answer: Internet providers generally don't provide wifi, because wifi is a poor system for large-scale networks.
In some cities, free wifi is available and you may be able to use that, but that's both insecure and has poor performance.
There are wifi repeaters and outdoor antennas, they are mostly marketed for use on campsites etc.

Wifi signal antenna


Permutation algorithm to minimize series change

Question: I have pieces that need to be paint with 2 colors. For example:
(Pc1 - Red - Blue)
(Pc2 - Yellow - Green)
(Pc3 - Yellow - Red)
(Pc4 - Black - Yellow)
I'm looking for an algorithm to find the best permutation to minimize the series change.
In my example the order 1 -> 2 -> 3 -> 4 implies 4 paints change, whereas 2 -> 4 -> 3 -> 1 only need 3 changes.
I've tried a brute force with Heap permutation, but it can only handle 10 pieces, then there are two many possible permutations.
I've tried to remove the "double single colors" (for example Pc5 - Pink - Purple) it doesn't reduce enough the list (~30 items)
I've tried @Stef solution, but the result is wrong, wih many occurences of the same object. I think it's because some objects have 2x the same colour, for example ['yellow', 'yellow']. Here is my sample: [[' 254 C PURPLE', ' 2C NOIR'], ['YELLOW C', 'BLEU 072 C'], [' 342 C GREEN', ' 430 C  GREY'], [' 254 C PURPLE', 'WHITE'], [' 392 C KAKI ', ' 392 C KAKI'], [' 342 C GREEN ', ' 342 C GREEN'], ['RUBINE RED C', ' 153 C OCRE'], [' 196 C MAUVE', ' VERT 375 C'], ['YELLOW C', 'YELLOW C'], [' 331 C VERT', ' 331 C VERT'], [' 072 C BLEU', ' 155 C BEIGE'], [' 263 C VIOLET', 'BLEU 072 C'], ['GREEN C', ' 153 C OCRE'], [' 427 C GRIS', 'RUBINE RED  C'], ['YELLOW C', ' 254 C PURPLE'], ['PROCESS BLUE C', ' 342 C GREEN']]
The output is [2, 8, 1, 8, 10, 7, 12, 6, 15, 5, 11, 4, 8, 14, 8, 9, 13, 8, 0, 3], with several occurences of the 8.
Comment: Hello, I suspect the first paragraph of your post makes a lot of sense in your head; but it is actually hard to read and parse and understand for someone who does not already know about your problem. Would you consider adding pictures to better illustrate this example?
Answer: Your problem can be rephrased as a particular case of the Traveling salesman problem, with edges constrained to have a length of 0, 1 or 2. Consider the graph with one vertex per piece, and a weighted edge between two vertices representing the number of colour-changes required between these two pieces. Then you're looking for a minimum-weight path that goes through all vertices exactly once.
Unfortunately, the travelling salesman problem is NP-hard even when restricted to edges of lengths 0, 1 and 2 as is your case. See Traveling salesman problem with small edge weights. Still, there are heuristics to solve it that might or might not be more efficient than your implementation of heap permutations.
For instance, using python library networkx:
import random
import networkx as nx
from itertools import combinations, pairwise

colours = ['crimson', 'honey', 'almond', 'cherry', 'navy', 'sky', 'dandelion', 'melon', 'lavender', 'lemon']
n_rooms = 30
room_colour = [random.sample(colours, k=2) for _ in range(n_rooms)]

print(room_colour)
# [['lemon', 'sky'], ['crimson', 'dandelion'], ['sky', 'crimson'], ['navy', 'lemon'], ['cherry', 'melon'], ['honey', 'dandelion'], ['lavender', 'melon'], ['lavender', 'lemon'], ['dandelion', 'almond'], ['lemon', 'navy'], ['almond', 'cherry'], ['melon', 'dandelion'], ['melon', 'honey'], ['navy', 'crimson'], ['lavender', 'cherry'], ['almond', 'honey'], ['navy', 'almond'], ['lavender', 'cherry'], ['lavender', 'lemon'], ['melon', 'almond'], ['cherry', 'lavender'], ['honey', 'lavender'], ['lavender', 'lemon'], ['melon', 'navy'], ['melon', 'navy'], ['melon', 'crimson'], ['honey', 'crimson'], ['honey', 'crimson'], ['lavender', 'melon'], ['honey', 'sky']]

def get_weight(i, j):
    return len(set(room_colour[i]+room_colour[j])) - 2

G = nx.Graph()
G.add_nodes_from(range(n_rooms))
G.add_weighted_edges_from((i, j, get_weight(i, j))
                          for i,j in combinations(range(n_rooms), 2))

permutation = nx.approximation.traveling_salesman_problem(G, cycle=False)

print(permutation)
print([room_colour[i] for i in permutation])
print('Total cost: ', sum(get_weight(i, j) for i,j in pairwise(permutation)))
# [11, 6, 28, 7, 22, 18, 3, 23, 24, 9, 16, 8, 2, 0, 29, 12, 4, 14, 20, 17, 21, 5, 15, 10, 19, 25, 1, 26, 27, 13]
# [['melon', 'dandelion'], ['lavender', 'melon'], ['lavender', 'melon'], ['lavender', 'lemon'], ['lavender', 'lemon'], ['lavender', 'lemon'], ['navy', 'lemon'], ['melon', 'navy'], ['melon', 'navy'], ['lemon', 'navy'], ['navy', 'almond'], ['dandelion', 'almond'], ['sky', 'crimson'], ['lemon', 'sky'], ['honey', 'sky'], ['melon', 'honey'], ['cherry', 'melon'], ['lavender', 'cherry'], ['cherry', 'lavender'], ['lavender', 'cherry'], ['honey', 'lavender'], ['honey', 'dandelion'], ['almond', 'honey'], ['almond', 'cherry'], ['melon', 'almond'], ['melon', 'crimson'], ['crimson', 'dandelion'], ['honey', 'crimson'], ['honey', 'crimson'], ['navy', 'crimson']]
# Total cost:  23


Hooking internal function: How do the the parameters look like?

Question: I have already been using Easyhook in C# to hook functions of the WINAPI.
Now I am trying to hook an internal function of a program to log a specific "event".
I have been able to discover the function call with the "Ultimap"-Function of Cheat Engine:
008AEC40   /$  6A FF             PUSH -1
008AEC42   |.  68 E37EC100       PUSH Progra.00C17EE3
008AEC47   |.  64:A1 00000000    MOV EAX,DWORD PTR FS:[0]
008AEC4D   |.  50                PUSH EAX
008AEC4E   |.  51                PUSH ECX
008AEC4F   |.  56                PUSH ESI
008AEC50   |.  A1 4093F600       MOV EAX,DWORD PTR DS:[F69340]
008AEC55   |.  33C4              XOR EAX,ESP
008AEC57   |.  50                PUSH EAX
008AEC58   |.  8D4424 0C         LEA EAX,DWORD PTR SS:[ESP+C]
008AEC5C   |.  64:A3 00000000    MOV DWORD PTR FS:[0],EAX
008AEC62   |.  8BF1              MOV ESI,ECX
008AEC64   |.  897424 08         MOV DWORD PTR SS:[ESP+8],ESI
008AEC68   |.  E8 033CFFFF       CALL Progra.008A2870
008AEC6D   |.  C74424 14 0000000>MOV DWORD PTR SS:[ESP+14],0
008AEC75   |.  8B4424 1C         MOV EAX,DWORD PTR SS:[ESP+1C]
008AEC79   |.  50                PUSH EAX
008AEC7A   |.  8D4E 24           LEA ECX,DWORD PTR DS:[ESI+24]
008AEC7D   |.  C706 18E8CD00     MOV DWORD PTR DS:[ESI],Progra.00CDE818
008AEC83   |.  E8 F8E7FFFF       CALL Progra.008AD480
008AEC88   |.  C74424 14 FFFFFFF>MOV DWORD PTR SS:[ESP+14],-1
008AEC90   |.  8BC6              MOV EAX,ESI
008AEC92   |.  8B4C24 0C         MOV ECX,DWORD PTR SS:[ESP+C]
008AEC96   |.  64:890D 00000000  MOV DWORD PTR FS:[0],ECX
008AEC9D   |.  59                POP ECX
008AEC9E   |.  5E                POP ESI
008AEC9F   |.  83C4 10           ADD ESP,10
008AECA2   \.  C2 0400           RETN 4

The function gets called here:
008CAF5F    .  85F6              TEST ESI,ESI
008CAF61    .  74 29             JE SHORT Progra.008CAF8C
008CAF63    .  6A 32             PUSH 32
008CAF65    .  8D5424 4C         LEA EDX,DWORD PTR SS:[ESP+4C]
008CAF69    .  52                PUSH EDX
008CAF6A    .  8D8F DC120000     LEA ECX,DWORD PTR DS:[EDI+12DC]
008CAF70    .  E8 2BF4F4FF       CALL Progra.0081A3A0
008CAF75    .  C68424 A4000000 1>MOV BYTE PTR SS:[ESP+A4],13
008CAF7D    .  834C24 14 40      OR DWORD PTR SS:[ESP+14],40
008CAF82    .  50                PUSH EAX
008CAF83    .  8BCE              MOV ECX,ESI
008CAF85    .  E8 B63CFEFF       CALL Progra.008AEC40    #### FUNCTION CALL ####
008CAF8A    .  EB 02             JMP SHORT Progra.008CAF8E
008CAF8C    >  33C0              XOR EAX,EAX
008CAF8E    >  C78424 A4000000 1>MOV DWORD PTR SS:[ESP+A4],14
008CAF99    .  8B95 F0130000     MOV EDX,DWORD PTR SS:[EBP+13F0]
008CAF9F    .  6A 01             PUSH 1
008CAFA1    .  8D7424 38         LEA ESI,DWORD PTR SS:[ESP+38]

Right now I am trying to learn more about ASM (calling conventions etc.). This tutorial is very good but I still don' t know how to deal with the function above.
How might the function argument(s) look like?
When breaking at the function call, the information (a simple Integer) I try to "extract" via hooking is stored in EBX, which unfortunately isn' t accessed once. So I have look for a function, where this value is passed as an argument, right?
Answer: The function 008AEC40 appears to be using the thiscall calling convention. The first argument, the this pointer is passed in ECX. The rest of the arguments are pushed on the the stack in right to left order. This particular function, a method of C++ class, only takes one argument in addition to its implicit this pointer.
Comment: Thank you very much. Do you know any books / tutorials to start with about reverse engineering C++ applications?


Sublevel set estimate

Question: Let $f\in C^2([a,b]\to\mathbb{R})$ and $|f''(x)|\geq\lambda$ for all $x\in[a,b]$ and some $\lambda>0$. Let $\alpha>0$ and
\begin{equation}
E = \{ x:|f'(x)|\leq\alpha \}
\end{equation}
Show that $E$ is a closed interval and
\begin{equation}
\Big| E \Big| \leq 2 \frac{\alpha}{\lambda}.
\end{equation}
I know this is a special case for a sublevel set estimate, where $k=2$, but I don't know a simple way to prove it without using Chebyshev polynomials. I already showed $E$ is a closed interval.
Thank you.
EDIT: It's not for some constant $C$; I changed the constant to be 2.
Answer: It is easy to show that E is closed because $f^{'}$ is monotone and continuous and according to a theorem in Analysis if $I$ is a closed interval so is $f^{' -1}(I)$. But I don't get the second part of the question it is obvious that there is a C with that property! It's sufficient to take C bigger than $\lambda \rvert E\lvert/ \alpha $!!
Comment: @dh87: Oh, my bad. I meant $f''(x) \frac1{f''(x)}$. I would say substitution, as there is already the derivative of $f'$. Just remember that $f'$ has an inverse.
Comment: Thanks for your answer. I would like the constant $C$ to be $2$. How can I get this number? Thank you.
Comment: @dh87: $|E| = \int_E f'(x) \frac1{f'(x)} \mathrm d x$ where $E=[a,b]$ is some interval.
Comment: @user251257 Thank you. Can you please elaborate more? Am I integrating by parts?
Comment: Oh, I see it now. Thank you so much!!!

Sublevel set estimate


How do I fix my kitchen ceiling?

Question: How do I fix my kitchen ceiling? I have the ceiling covering peeling off. It has exposed cracks where water has possibly come through from the tiles above. So, how do I fix my kitchen ceiling?
Answer: From what I see in your pics, you have a plaster ceiling that is failed. Usually water is the culprit for delaminating the scratch from the finish coats.
You have two options to repair this.
First option is to remove all loose plaster down to the lathe and replace it with new plaster. This is not as easy as it may sound. Working with real plaster takes some skill and practice. Matching the original texture of the finish can be tricky.
Second option is to recoat the entire ceiling with a layer of 3/8" drywall. Although this may be a bit larger job, it will secure any loose, soon to fail plaster. The new drywall ceiling will be clean and smooth if taped properly and give many years of service. I have found that once a plaster ceiling starts to fail, it will usually continue to get worse.
Comment: But before any of that - solve the water issue.  Make sure there's not still water coming down onto the ceiling or fixing it will be a very short term fix.
Comment: @ Evil,  good call.

How do I fix my kitchen ceiling?


jQuery-ui dialog - hide buttons using jquery

Question: How do I remove/hide the "Ok" button dynamically using jquery?
$('#dialog-save').dialog({
            autoOpen: false,
            modal: false,
            draggable: true,
            width: 275,
            height: 175,
            buttons: {
                "Ok": function () {
                    $(this).dialog("close");
                }
            }
        });

I was able to change the title using this code -
var saveDialog = $('#dialog-save');
saveDialog.dialog('option', 'title', 'Message');

Not sure how to remove the buttons. Thanks!
Comment: You can also consider just including an id when you create the button, so that you can access and manipulate it later (see below).
Answer: You can set the buttons option in the same way you are setting the title:
saveDialog.dialog("option", "buttons", {});

Pass in an empty object literal to remove all the buttons. That should be fine, since you appear to only have the one button. If you were to have others, just specify the ones you want to keep when you call the option method.
Comment: You beat me to it. I was going to answer the question myself. Works perfectly. Thank you very much!
Answer: One commonly overlooked feature of the UI dialog is that you can set various other properties of the buttons, including 'class' and 'id'. These can be very useful if you need to manipulate the buttons after instantiation.
For example...
$('#dialog-save').dialog({
        autoOpen: false,
        modal: false,
        draggable: true,
        width: 275,
        height: 175,
        {
            id: 'okBtn',
            text: "Ok",
            click: function () {
                $(this).dialog("close");
            }
        }]
    });

// And then at some other point in the code...
$('#okBtn').remove();

Answer: Juste like this won't show the button :
$('#dialog-save').dialog({
        autoOpen: false,
        modal: false,
        draggable: true,
        width: 275,
        height: 175
        }
    });

And if you want to remove them after you have shown the dialog
Maybe something like this;
How can I disable a button in a jQuery dialog from a function?
Answer: Try this fiddle
$(function(){
    $('#dialog-save').dialog({
            autoOpen: false,
            modal: true,
            draggable: true,
            width: 275,
            height: 175,
            buttons: {
                "Ok": function () {
                    $(this).dialog("close");
                }
            }
    });
    $('#dialog-save').dialog('open');
    $('.change').click(function(){
        $('#dialog-save').dialog("option",{buttons:{}});
        $('#dialog-save').dialog('open');
    });
});


Access Project online api on sharepoint online on c#

Question: I have a sharepoint (myAzure.sharepoint.com). Inside I got a site PWA (project online). PWA offert OData Api. The security of that Api required a User member of your AD (not an app).
I want, in c#, to consumme the api outside azure (like localhost). I need to do it without interractive (web promp interraction with the user).
Answer: The only way I found was by "password credential".
<code>string url = $"https://login.microsoftonline.com/{myTenantId}/oauth2/v2.0/token";
var formData = new NameValueCollection();
formData.Add("client_id", clientId);
formData.Add("client_secret", clientSecret);
formData.Add("username", username);
formData.Add("password", password);
formData.Add("scope", $"https://{myAzure}.sharepoint.com/.default");
formData.Add("grant_type", "password");
string encodedFormData = string.Join("&", Array.ConvertAll(formData.AllKeys, key =>
string.Format("{0}={1}", Uri.EscapeDataString(key), Uri.EscapeDataString(formData[key]))));

var request = (HttpWebRequest)WebRequest.Create(url);
request.Method = "POST";
request.ContentType = "application/x-www-form-urlencoded";

byte[] formDataBytes = Encoding.UTF8.GetBytes(encodedFormData);
request.ContentLength = formDataBytes.Length;
using (var requestStream = request.GetRequestStream())
{
    requestStream.Write(formDataBytes, 0, formDataBytes.Length);
}

using (var response = (HttpWebResponse)request.GetResponse())
{
    using (var responseStream = response.GetResponseStream())
    {
        if (responseStream != null)
        {
            using (var reader = new System.IO.StreamReader(responseStream))
            {
                string responseContent = reader.ReadToEnd();
                JObject jsonResponse = JObject.Parse(responseContent);
                string accessToken = (string)jsonResponse["access_token"];

                using (HttpClient client = new HttpClient())
                {
                    client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", accessToken);
                    HttpResponseMessage response2 = await client.GetAsync($"https://{myAzure}.sharepoint.com/sites/{myPWASite}/_api/ProjectData/Ressources");

                    if (response2.IsSuccessStatusCode)
                    {
                        string responseBody = await response2.Content.ReadAsStringAsync();
                        Console.WriteLine(responseBody);
                    }
                    else
                    {
                        Console.WriteLine("Erreur: " + response.StatusCode);
                    }
                }
            }
        }
    }
}
</code>

Explanatory documentation

https://learn.microsoft.com/en-us/azure/active-directory/develop/v2-oauth-ropc
https://techcommunity.microsoft.com/t5/project-support-blog/app-user-authentication-and-project-online-development/ba-p/1925443
https://learn.microsoft.com/en-us/azure/data-factory/connector-odata?tabs=data-factory#copy-data-from-project-online


Flexible PVC to flexible metal conduit connector

Question: I had planned to install a new run using flexible PVC conduit, but discovered a section of metal conduit already in place within a wall I can reuse. Is there a way to directly connection PVC and metal flexible conduit without needing a junction box?
I'm not adverse to using a junction box, just thought a direct connector would save time & effort.
Thanks.
i.e. connecting these two conduits...
Comment: What's the reasoning behind using LFNC instead of ENT (smurf tube) for the new run?
Answer: Yes you can convert from liquid tight to metal flex you need a end for each and a coupling to connect the two. If both are 1/2" for example a standard 1/2" conduit coupling Will allow the two to be connected without a box.


Local source of Terraform AWS provider

Question:
What specific syntax needs to be used in the example below in order for Terraform to source the AWS provider from a given path in the local file system instead of requesting a cloud copy from the remote Terraform Registry?

provider "aws" {
  region     = var._region
  access_key = var.access_key
  secret_key = var.secret_access_key
}

Something like src=C:\path\to\terraform\aws\provider\binary
I recall Mitchel Hashimoto explaining that this is a new feature during HashiConf, but I cannot seem to find documentation.
Answer: You should be able to set it in the CLI configuration as described in the documentation:
provider_installation {
  filesystem_mirror {
    path    = "/usr/share/terraform/providers"
    include = ["example.com/*/*"]
  }
  direct {
    exclude = ["example.com/*/*"]
  }
}

Local source of Terraform AWS provider