Showers in house run cold after 30/45 seconds - Sinks scalding hot?

Question: Have a two story house with kitchen, main bath, guest toilet and laundry room on first floor, and two bedrooms upstairs with one full bath each. The water heater is a 55 gal gas operated, located in the crawl space. There is an expansion/pressurized tank on the hot water line of the house as well.
Yesterday, out of the blue and without any warning, the shower in the main bath went from hot to lukewarm then cold after about 30/45 seconds of running. The sink in the same bath would put out scalding hot water, as did the kitchen sink and any other outlet in the 1st floor. Turning the mixer valve control to max hot puts out warmer water, just enough for one to shower.
Checked upstairs and one of the bathroom showers displays the same symptom, while the other one works fine. Again, all faucets in the 2nd floor put out hot water as expected.
I checked the anti-scald on both shower mix valves and these don't seem to have them (Price-Pfisters - MFD 2007), but after that I'm out of options. Today both showers continue to do the same, while the third one upstairs (the one least used) works fine.
Where should I start looking? Is it possible that both mixer valves would have gone bad at the same time? What else could be causing this?
Comment: Would you have noticed that the upstairs shower problem started the same day, or did you only notice it after the downstairs shower experienced problems? Swapping out the mixing valve is going to be the fastest way to identify if it's the problem.
Comment: BMitch, thanks for your response. I will look into the process to change the cartridge. Valve is PricePfister and I know they are lifetime warranty.
Comment: Folks, I wanted to let everyone know that I was able to fix this issue by replacing the cartridge. PF will ship these free for the first owner of a home (I'm technically the second owner here, since I bought it from the guy that built the subdivision and had my house as his personal residence for the past 7 yrs or so).
Comment: Two cartridges went bad at the same time?
Answer: Wait, there's an expansion tank in the HOT water side?  That's wrong, it's supposed to be on the cold-water side of the hot water heater.  Expansion tanks do not have heaters in them, so the water in them is cold!  Try this theory on for size: You turn on max-hot, until the water runs nice and hot.  The lengthy hot-water pipe from downstairs is now full of hot water.  Then you set it for mixed-warm, which flows a lot more water overall, and reduces system pressure.  What does the expansion tank do?  Equalize to that new pressure - the air in the tank expands, by pushing cold water out of the expansion tank into the "hot" line.  It gets upstairs 30 seconds later.
How do you test this?  First, when it gets cold, touch nothing - just let it keep flowing for 120 more seconds.  See if it goes back to normal if you wait long enough.  If so, I'd blame the expansion tank being on the wrong side.
Or check the tank's temperature - room temperature - then trigger the problem - and shut off everything and run back down and check the tank's temperature again.  If it's warmer, it just ingested some hot water - which means it recently pushed out some cold water.
Otherwise, I'd do some other experiments.  Shut off the cold supply to the shower.  Now if it does the hot-cold bounce, it can't be the mixing valve!  Turn the tub to hot max.  Let it get hot and watch for that bounce.  None? Throw open the sink faucet to COLD and flush the toilet, to simulate the extra flow of setting the shower to "warm".  Watch for the bounce again.  If it still happens, that means the (good) valve isn't getting good hot water.
What would make it suddenly break? Probably something minor upstream that wouldn't affect healthy plumbing. Maybe loose cruft in your piping (probably upstream of the hot water heater). Maybe in street piping.  Maybe the water company changed supply pressure.
Comment: Hi Wolf, I may have oversimplified the explanation. The expansion tank is in fact on the cold side of the Hot Water heater... I will look into the test of cutting cold water and seeing what that does. Will report back
Comment: I tried closing the cold water line to the shower but I wasn't able to do so since it did what Mysterfixit suggested. However I was able to close the valve on the expansion tank side, which made the shower run on full hot for as long as needed... Still a bit baffled by this, but I will see what the outcome is once mixing valves are replaced.
Comment: You may not be able to shut off the cold water to test the hot as the shower valve probably is a pressure balancing valve. No cold water pressure would made the hot drop to zero as well. That's so when someone flushes the toilet your shower doesn't suddenly get hotter.
Answer: It's possible some debris in the hot water line fouled the two most used shower cartridges. The least used one was spared because it wasn't in use when the debris passed through.
Do you have galvanized steel piping? If so a chunk of rust may have broken loose inside upstream and wound up in the shower valve.
Has any work been done recently in the hot water lines?
Comment: Mysterifix, piping is copper/brass (based on color). House is 6 or 8 years old at the most... I doubt rust is the issue. However, there were deposits on the AC drain line, so maybe some debries were formed somewhere and got loose? There wasn't any work done on the property at all.


How to integrate $\int \frac{2x^2+x}{(x+1)(x^2+1)}dx$?

Question: How to integrate $\displaystyle \int \frac{2x^2+x}{(x+1)(x^2+1)}dx$? I Tried using partial fractions but i got lost, thanks.
Answer: Partial fractions are the way to go. The fraction is already reduced, and the denominator is fully factored over the reals, so your setup is
$$\frac{2x^2+x}{(x+1)(x^2+1)}=\frac{A}{x+1}+\frac{Bx+C}{x^2+1}=\frac{A(x^2+1)+(Bx+C)(x+1)}{(x+1)(x^2+1)}\;,$$
and you must find $A,B$, and $C$ so that $$2x^2+x=A(x^2+1)+(Bx+C)(x+1)=(A+B)x^2+(B+C)x+(A+C)\;.$$
Equating coefficients of powers of $x$ yields the system
$$\left\{\begin{align*}
&A+B=2\\
&B+C=1\\
&A+C=0\;,
\end{align*}\right.$$
which is easily solved: $A=\frac12,B=\frac32$, and $C=-\frac12$. Thus,
$$\frac{2x^2+x}{(x+1)(x^2+1)}=\frac1{2(x+1)}+\frac{3x-1}{2(x^2+1)}\;,$$ and
$$\int\frac{2x^2+x}{(x+1)(x^2+1)}dx=\frac12\int\frac1{x+1}dx+\frac12\int\frac{3x-1}{x^2+1}dx\;.$$
You shouldn't have any trouble with $\int\frac1{x+1}dx$. The other term is most easily handled by splitting it:
$$\int\frac{3x-1}{x^2+1}dx=3\int\frac{x}{x^2+1}dx-\int\frac1{x^2+1}dx\;,$$
where the first integral succumbs to a $u$-substitution, and the second is one that you should know (or at least be able to work by a trig substitution).
Comment: There is a trick known as the "cover-up rule" which gets you the constants which go with linear factors - in the expression for $2x^2+x$ set $x=-1$ which immediately gives you an expression for $A$. In this case you could deal with the quadratic factor and get $B$ and $C$ by setting $x=\pm i$. It is called the cover-up rule because it is computable directly from the original expression for partial fractions by computing the LHS after covering up a factor in the denominator and evaluating what remains.
Comment: @Marvis: You're right, of course. I'm fixing it now.
Comment: @MarkBennet: I usually choose this "rule" for finding constants. It often works good.
Comment: @Mark: Interesting: I'd never heard it given a name. It's a nice shortcut, but I definitely think of it as an extra.
Answer: The key is to write $(2x^2 + x)$ as $A(x^2+1) + (Bx+C)(x+1)$
$$(2x^2 + x) = A(x^2+1) + (Bx+C)(x+1) = (A+B)x^2 + (B+C)x + (A+C)$$
This gives us $A+B = 2$, $B+C = 1$ and $A+C = 0$ i.e. $A+B = 2$ and $B-A = 1$.
$$A = \dfrac12, B = \dfrac32, C = -\dfrac12$$
Hence, $$\dfrac{2x^2+x}{(x+1)(x^2+1)} = \dfrac1{2(x+1)} + \dfrac{3x-1}{2(x^2+1)} = \dfrac1{2(x+1)} + \dfrac34 \dfrac{2x}{x^2+1} - \dfrac12 \dfrac1{x^2+1}$$
Now you should be able to integrate it.
Answer: From $\frac{2x^2+ x}{(x+ 1)(x^2+ 1)}= \frac{A}{x+ 1}+ \frac{Bx+ C}{x^2+ 1}$ you can add the fractions on the right, then compare coefficients of "like terms".  But we can also use the fact that this is to be true for all x.  Setting x to any three values gives three equations to solve for A, B, and C.
First multiplying both sides by $x+1$ and $x^2+ 1$ simplifies to $2x^2+ x= A(x^2+ 1)+ (Bx+ C)(x+ 1).
Setting x= -1 immediately gives $2(1)+ (-1)= 1= A(2)$ so $A= \frac{1}{2}$.
Setting x= 0 gives $0= A+ C= \frac{1}{2}+ C$ so $C= -\frac{1}{2}$.
Setting x= 1 gives $2+ 1= 3= 2A+ 2(B+ C)= 1+ 2B- 1$ so $B= \frac{3}{2}$.


Managing asynchronous communication: how to examine response received in another thread

Question: I have a dispatcher thread and a listener thread. When I dispatch a command, I want to wait for response before I send follow up command. Moreover I need to examine the respond before I can proceed with 2nd command, the least of which is to confirm the response is received and everything is okay. My pseudo code is below:
<code>void MainWindow::downloadData()
{
    dispatcher->getInfo(); // sends command

    // QString response = receiver->response() // idealy I would like to check response but since its async, i can't really do that!

    dipatcher->askData(); // the 2nd command and so forth

}
</code>
Is there any elegant way to solve this issue? The only way I can think of is if I use the same thread and all calls are blocking but that's not necessarily a good solution.
In Qt, I could use signals and slots to connect them in cascading manner so when the first signal is triggered it initiates the whole sequence of operation (each slot emitting a new signal) but seems rather dirty as well.
Comment: It's event-driven programming. It could be clean if you do it right.
Comment: @user3528438 Lets say I am issuing three commands when user press a button to accomplish something. If I wire each command to signal and slot which will establish a chain of events, that seems rather cumbersome. The commands are low level and they are better independent. I feel like rest of the system should use the commands,the command shouldn't dictate what happens next!?
Comment: The dispatcher/listener thread split is unnecessary. It can all be handled from one thread. You need a request object, or a request handler object that issues signals when the result of a request is available. This can then guide a `QStateMachine` whose states issue further requests. Parts of the state machine can be automatically generated - say, suppose that you have a list of requests to issue without doing special processing between them - you can generate the needed states programmatically.
Comment: You don't need multiple threads if you're processing sequentially. You can also just add all commands to a queue and process them from the front until the queue is empty.
Comment: I am using `QTcpServer` derived class and its `listen()` function, it just listens on a port so I should use `listen()` when I need it and `close` when I am am done listening?
Answer: One of the most robust ways to handle asynchronous events and process a chains/graphs of actions upon these events are FSMs. Qt provides a basis for implementing FSMs with its Qt-State machine framework. I'd suggest to go this way. Unfortunately all the examples provided by Qt for FSM are dealing with GUIs and animations.
The advantage of FSM approach is, FSMs can be represented both as graphs and as tables. The first option is great for understanding, the second for validation, that there are no endless loops and "dead" ends.
I've built on basis of Qt-FSM framework own framework for defining FSMs in a domain specific language. I use it for controlling a complex machine having couple of sensors actors all working asynchronously. Using DSL helps me to implement in higher abstraction - in the abstraction level of FSM-graphs.


Validate list of ints in FluentValidation

Question: How do you validate a list of ints using fluent validation?
My model has:
 public List<int> WindowGlassItems { get; set; }

Model Validator has
RuleFor(x => x.WindowGlassItems).SetCollectionValidator(new WindowGlassItemsValidator());

  public class WindowGlassItemsValidator : AbstractValidator<int>
    {
        public WindowGlassItemsValidator()
        {
            RuleFor(x=>x).NotNull().NotEqual(0).WithMessage("GLASS REQ");
        }
    }

Im getting:
Property name could not be automatically determined for expression x => x. Please specify either a custom property name by calling 'WithName'.
Answer: You are seeing that error because you the RuleFor method is expecting a property to be specified. I have been unable to get CollectionValidators to work with primitive types like you have. Instead, I use a custom validation method with Must like this.
The only problem I have with this approach is I am unable to avoid repeating the error message across the 2 validations. If you don't require it when the list is null, you can leave it out after the NotNull call.
    RuleFor(x => x.WindowGlassItems)
        //Stop on first failure to avoid exception in method with null value
        .Cascade(CascadeMode.StopOnFirstFailure)
        .NotNull().WithMessage("GLASS REQ")
        .Must(NotEqualZero).WithMessage("GLASS REQ");

    private bool NotEqualZero(List<int> ints)
    {
        return ints.All(i => i != 0);
    }

Comment: Whilst this didn't entirely fix it, it certainly helped a lot, thanks
Answer: I have got the same problem with a List and this was my solution:
RuleFor(rule => rule.MyListOfMyEnum).SetCollectionValidator(new
EnumValidator());
public class EnumValidator<T> : AbstractValidator<T>
{
    public EnumValidator(params T[] validValues)
    {
        var s = validValues.Length == 0 ? "---" : string.Join(",", validValues);
        RuleFor(mode => mode).Must(validValues.Contains).WithMessage("'{PropertyValue}' is not a valid value. Valid are [{0}].", s);
    }

    public EnumValidator()
    {
        var s = typeof (T).Name;
        RuleFor(mode => mode).IsInEnum().WithMessage("'{PropertyValue}' is not a valid value for [{0}].", s);
    }
}


draw $\triangle ABC$ in which $AB=5.5$cm, $\angle C =40^{\circ}$ and $BC-AC=2.5$cm

Question: I tried this question whole day but could not find its solution I have also not got a clue please help me in doing it
Comment: With such a terse problem statement, wholly contained in the title, you are short-changing your Readers.  Please use the body of the Question to state the problem and explain where your difficulty lies.
Answer: Draw a triangle $ABD$ with $AB=5.5\,\mathrm{cm}$ and $\angle D=110^\circ$ and $BD=2.5\,\mathrm{cm}$. Then extend $BD$ and intersect with the line through $A$ at angle $70^\circ$ with $AD$ to find $C$.
This makes $\triangle DAC$ isosceles with $\angle C=40^\circ$ and thereby the conditions are met.
Comment: (+1) Nice solution. I took the liberty to add a diagram to improve it, I hope you do not mind.


Pandas fill missing values of a column based on the datetime values of another column

Question: Python newbie here, this is my first question.
I tried to find a solution on similar SO questions, like this one, this one, and also this one, but I think my problem is different.
Here's my situation: I have a quite large dataset with two columns: Date (datetime object), and session_id (integer). The timestamps refer to the moment where a certain action occurred during an online session.
My problem is that I have all the dates, but I am missing some of the corresponding session_id values. What I would like to do is to fill these missing values using the date column:

If the action occurred between the first and last date of a certain session, I would like to fill the missing value with the id of that session.
I would mark as '0' the session where the action occurred outside the range of any session -
and mark it as '-99' if it is not possible to associate the event to a single session, because it occurred during the time range of different session.

To give an example of my problem, let's consider the toy dataset below, where I have just three sessions: a, b, c. Session a and b registered three events, session c two. Moreover, I have three missing id values.
   |       DATE          |sess_id|
----------------------------------
 0 | 2018-01-01 00:19:01 | a    |
 1 | 2018-01-01 00:19:05 | b    |
 2 | 2018-01-01 00:21:07 | a    |
 3 | 2018-01-01 00:22:07 | b    |
 4 | 2018-01-01 00:25:09 | c    |
 5 | 2018-01-01 00:25:11 | Nan  |
 6 | 2018-01-01 00:27:28 | c    |
 7 | 2018-01-01 00:29:29 | a    |
 8 | 2018-01-01 00:30:35 | Nan  |
 9 | 2018-01-01 00:31:16 | b    |
10 | 2018-01-01 00:35:22 | Nan  |
...

[Image_Timeline example][1]

This is what I would like to obtain:
   |       DATE          |sess_id|
----------------------------------
 0 | 2018-01-01 00:19:01 | a    |
 1 | 2018-01-01 00:19:05 | b    |
 2 | 2018-01-01 00:21:07 | a    |
 3 | 2018-01-01 00:22:07 | b    |
 4 | 2018-01-01 00:25:09 | c    |
 5 | 2018-01-01 00:25:11 | -99  |
 6 | 2018-01-01 00:27:28 | c    |
 7 | 2018-01-01 00:29:29 | a    |
 8 | 2018-01-01 00:30:35 | b    |
 9 | 2018-01-01 00:31:16 | b    |
10 | 2018-01-01 00:35:22 | 0    |
...

In this way I will be able to recover at least some of the events without session code.
I think that maybe the first thing to do is to compute two new columns showing the first and last time value for each session, something like that:
foo['last'] = foo.groupby('sess_id')['DATE'].transform(max)
foo['firs'] = foo.groupby('SESSIONCODE')['DATE'].transform(min)

And then use first-last time value to check whether each event whose session id is unknown falls withing that range.
Answer: Your intuition seems fine by me, but you can't apply it this way since your dataframe foo doens't have the same size as your groupby dataframe. What you could do is map the values like this:
foo['last'] = foo.sess_id.map(foo.groupby('sess_id').DATE.max())
foo['first'] = foo.sess_id.map(foo.groupby('sess_id').DATE.min())

But I don't think it's necessary, you can just use the groupby dataframe as such.
A way to solve your problem could be to look for the missing values in sess_id column, and apply a custom function to the corresponding dates:
def my_custom_function(time):
    current_sessions = my_agg.loc[(my_agg['min']<time) & (my_agg['max']>time)]
    count = len(current_sessions)
    if count == 0:
        return 0
    if count > 1:
        return -99
    return current_sessions.index[0]

my_agg = foo.groupby('sess_id').DATE.agg([min,max])
foo.loc[foo.sess_id.isnull(),'sess_id'] = foo.loc[foo.sess_id.isnull(),'DATE'].apply(my_custom_function)

Output:
    DATE                    sess_id
0   2018-01-01 00:19:01     a
1   2018-01-01 00:19:05     b
2   2018-01-01 00:21:07     a
3   2018-01-01 00:22:07     b
4   2018-01-01 00:25:09     c
5   2018-01-01 00:25:11     -99
6   2018-01-01 00:27:28     c
7   2018-01-01 00:29:29     a
8   2018-01-01 00:30:35     b
9   2018-01-01 00:31:16     b
10  2018-01-01 00:35:22     0

I think it performs what you are looking for, though the output you posted in your question seems to contain typos.
Comment: Thank you for your help! Indeed, there was a small typo in the output, i'm going to fix it. Could I just ask you to clarify what the last return (return current_sessions.index[0]) does?
Comment: No problem, in case that there is exactly one session which match the test (ie which begins before the given time and ends after), we retrieve its name. Indeed the data frame `my_agg` is given by a groupby on `sess_id` which means its index is composed of values from `sess_id`. When we only have one session in its index, `current_sessions.index[0]` allows us to retrieve this `sess_id` value. Is it clear?
Comment: in `my_custom_function` I have some if statements. These are here to check how many sessions are open at the time we're looking at. The first `if count == 0` activates when no session is open, the second `if count > 1` is for when you have multiple open sessions, so that when you reach the last `return` you must have only one open session.
Comment: It's clear. So, let's say that we have more session in the index, as more than just one match the test, what could we do? Maybe change to if count ==1 return current_session.index? In any case thank you for the clear explanation, I really appreciated it.
Comment: It depends on what your are trying to return, I understood from your question that if you couldn't link the time to a unique session, you should get `-99` as a result. Am I wrong?
Comment: No, you were right. Thank you for your teaching, they really helped me much.


How to execute an Array job on SGE -

Question: I have 50 different fasta files that I would like to analyze using a program (glsearch36).
The files are numbered 3163proph00.fa - 3163proph49.fa.
I would like to submit these 50 almost identical jobs using to a cluster using SGE queuing system as an array job.
One problem is that SGE requires the SGE_TASK_ID to be from 1-50, so I first had to create the variable i and subtract 1 to get 0. I then created j as the numbers have a leading zero.
I am not too proficient with bash, so I am sure that I have made some syntax error in going from SGE_TASK_ID to i to j.
When I submit this file I get the following error "Illegal variable name.".
Any help would be appreciated.
Thank you,
#!/bin/bash
#$ -cwd
#$ -t 1-50
#$ -e glsearch.err
#$ -o glsearch.out
#$ -N glsearch

#  really the files are 00-49
i=$(($SGE_TASK_ID - 1))
j= printf "%02d" "$i"
echo $j
/g/bor/x86_64/bin/glsearch36 -T 1 /g/bor/Viruses/3163_proph_split50/3163proph$j.fa /g/bor/Viruses/prophage_region.fna > glsearch_3163proph$j.txt

Answer:
$ in the ((...)) is not needed
no space before and after =
put printf into $(...)
i=$((SGE_TASK_ID - 1))
j=$(printf "%02d" "$i")

Comment: Thanks kev - I made your modifications but am still getting the same illegal variable name error.
Comment: did you `export SGE_TASK_ID` before running the script. Please put `echo $SGE_TASK_ID` in the script to debug.
Comment: SGE_TASK_ID is being assigned properly.  However, i and j aren't being assigned. I echoed them and they are blank.
sge task id 44
Comment: Can you run the `glsearch36` command in the shell successfully?
Comment: yes I can run glsearch.  to debug I have commented out the glsearch and am just trying to get it to echo $i and $j and I am still getting the illegal variable name error.
Comment: This is very Weird. Try to remove all comments starts with `#$`.
Comment: If it still not work. Delete everything. Just put `echo hello world` in it.
Comment: Yes strange. the i and j assignments work in isolate when just typed into the shell.  However, within the submission script they don't work.
Comment: Got it!!  I just added "#$ -S /bin/sh" to the shell script and it is working now.
Answer: I suspect your job is running in a posix_compliant queue with /bin/csh as the default shell.  Because the queue is posix_compliant your #!  line is ignored and the default shell is used.  You can override the default shell with a -S directive to grid engine.
#$ -S /bin/bash

How to execute an Array job on SGE -


Why the code stops working when I start using localStorage?

Question: The code below is only working when I remove the componentWillMount that uses localStorage. With usage localStorage it gives a mistake

this.state.interests.map is not a function

I tried to move usage of localStorage out of component but it won't help. I suppose that using local storage somehow changes this.state.interests that they stop being an array.

let interests = ["Музыка", "Компьютеры", "Радио"]
let ListOfInterest = React.createClass({
  getInitialState: function() {
    return {value: '', interests: interests};
  },
  componentWillMount() {
    let local = localStorage.getItem('interests')
    if (local) {
      this.setState({interests: local});
    } else {
      localStorage.setItem('interests', this.state.interests)}
  },
  deleteInterest(key) {
    delete interests[key]
    this.setState(this.state) // without this line the page will not re-render
  },
  addInterest() {
    interests.unshift(this.state.value)
    this.setState({value: ''})
  },
  handleChange(event) {
    this.setState({value: event.target.value})
  },
  render() {
    return

      Интересы

      {this.state.interests.map((int, index) => {
        return <button onClick={() => {
          this.deleteInterest(index)
        }} key={index} className="btn-interest">{int}</button>
      })}
      <input type='text' placeholder="Add" value={this.state.value} onChange={(e) => this.handleChange(e)}/>
      <button onClick={() => {
        this.addInterest()
      }} className="add">Add interest</button>

  }
})

Comment: You have to stringify the array before storing it in local storage, and unstringify (parse) it on the way back out.
Comment: `this.setState(this.state)` looks horrible!
Comment: Are you working with the author of http://stackoverflow.com/questions/40788157/warning-js45-warning-setstate-can-only-update-a-mounted-or-mounting-comp ?
Comment: check if your local in componentWillMount() is an array or not
Comment: This does not provide an answer to the question. Once you have sufficient [reputation](http://stackoverflow.com/help/whats-reputation) you will be able to [comment on any post](http://stackoverflow.com/help/privileges/comment); instead, [provide answers that don't require clarification from the asker](http://meta.stackexchange.com/questions/214173/why-do-i-need-50-reputation-to-comment-what-can-i-do-instead). - [From Review](/review/low-quality-posts/14394894)
Answer: You have several issues in your example

in localStorage.setItem second argument have to be a String, you can not store Array(when you do it, in storage will be string separated by coma because called method toString - [1, 2, 3].toString() ), you need stringify array before set to Storage

keyValue A DOMString containing the value you want to give the
  key you are creating/updating.

localStorage.setItem(
   'interests', JSON.stringify(this.state.interests)
)

and parse when get value
let local = JSON.parse(localStorage.getItem('interests'));

this.setState(this.state) this is not good way to update state, you need update state like so
deleteInterest(key) {
  this.setState({
    interests: this.state.interests.filter((el, i) => i !== key)
  })
},

addInterest() {
  this.setState({
    value: '',
    interests: this.state.interests.concat(this.state.value)
  });
},

Example


water hammer after a regulator is added to system

Question: my local water dept changed my meter from a star meter to a setup that has an s bar with a regulator.lived here over 30 years and never had a regulator and never checked pressure.have hammer very bad when flushing toilets with regulaor set at 55 psi.remove regulator and add a jumper hammer stops but my psi is 95. what is causing hammer? thanks for any input.
Comment: Something's wrong - can't imagine that a lower pressure causes hammer.  Sounds like the hammer is happening inside the new equipment.  Maybe check with a plumber to see if a ballast tank can be added right there.
Answer: You may have air chambers that drained during the meter installation and refilled with water, rather than air.
First, check that any existing air chambers are working. You may need to shut the main valve and completely drain the system for a while to get air back into the chambers. Most are inaccessible, inside walls, so are not easily replaced, but you can add another chamber elsewhere.
Also make sure that pipe brackets (hangers) are firmly mounted, since a loose pipe exacerbates the issue.


Application of the Weierstrass M-Test

Question: I want to show that $\sum_{k=0} ^n z^k $, $ \; |z| <1$, converges using the M-test.
So I want to choose $M_k = r^k$ for some $|z| \leq r <1$, where we want $r$ to be a fixed number.

If $z$ is fixed, I just fix the $r$ based on $z$.
But I think $z^k$ is a function of $z$ (for each $k$), so how can I fix $r$?

$\\$

From wiki

Suppose that {$f_n$} is a sequence of complex-valued functions defined on a $A$, and that there is a sequence of positive numbers $M_n$ satisfying
$$\forall n \geq 1, \forall x \in A: \ |f_n(x)|\leq M_n,$$
$$\sum_{n=1}^{\infty} M_n < \infty$$
Then the series
$\sum_{n=1}^{\infty} f_n (x)$
converges absolute and converges  uniformly $A$.

This say that we want $M_k$ to an upper bound for $z^k$ for all $z$,but  I don't understand how we can fix an $r$ unless we ignore the potential values of $z$ where $|z| > r$.
Answer: Is not so obvius using the M-Weierstrass test, but you can easly show it for $|z|<1-\delta$ taking $r \in (1-\delta ,1)$ then since is valid for all $1>\delta>0$ then aproach the limit
$M_n= r^n$

Application of the Weierstrass M-Test


Culture building destroyed (not disabled) if I build one as different culture?

Question: My understanding was that when a character of a different culture takes over a barony, the cultural building of the previous culture is disabled.
This happened in my situation, I was Dutch culture with a Large Goedendag Militia Quarters (3rd tier cultural building). My inheritor was Italian culture, so that building disappeared and I was presented with the option of build the tier 1 Italian cultural building. I had done so, and later on I managed to restore Dutch culture to my heirs. The Godendag quarters were wiped out, I had to start at tier 1 again.
My question is two-fold:

Am I right in my original understanding? If I change culture and don't build a new cultural building, will it the original building restored if I switch back to my original culture?
Since I build a new building, is what I experienced a bug, or working as designed? (in case of bug, my current build is 2.1.4 checksum XQSJ)
Answer: No in both cases. When a castle gets a ruler with a new culture, then culture-specific buildings are lost forever, you should start anew. And it's not a bug.
Comment: Further play seems to confirm what you say.


not updating entity in viewmodel after post request using ajax

Question: I am new to knockout.js and i am using post method to update data into database . Here is my code
 <%@ Page Language="C#" AutoEventWireup="true" CodeFile="SProduct.aspx.cs" Inherits="SProduct" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

    <title></title>

    <form id="form1" runat="server">

            Knockout CRUD Operations with ASP.Net Form App

            List of Products

                        ID

                        Name

                        Category

                        Price

                        Actions

                        <button data-bind="click: $root.edit">
                            Edit</button>
                        <button data-bind="click: $root.delete">
                            Delete</button>

                        Total :

                    Update Product

                    ID

                    Name
                <input data-bind="value: Product().Name" type="text" title="Name" />

                    Category
                <input data-bind="value: Product().Category" type="text" title="Category" />

                    Price
                <input data-bind="value: Product().Price" type="text" title="Price" />

                <button data-bind="click: $root.update">
                    Update</button>
                <button data-bind="click: $root.cancel">
                    Cancel</button>

                    Add New Product

                    Name
                <input data-bind="value: $root.Name" type="text" title="Name" />

                    Category
                <input data-bind="value: $root.Category" type="text" title="Category" />

                    Price
                <input data-bind="value: $root.Price" type="text" title="Price" />

                <button data-bind="click: $root.create">
                    Save</button>
                <button data-bind="click: $root.reset">
                    Reset</button>

    </form>

Updated

Here is screen shot of my page . when i click on update ajax success function is called, but no change in above table field .
Comment: You are returning one `Product` from your `Update` so it does not return a list. Just remove the `self.Products.removeAll();                        self.Products(data.d);` lines completely from the success method if you viewmodels are wired correctly it is enough to null out the `Poduct` property.
Comment: but it will not change the updated value in a table which is just above that form .
Comment: @nemesv check please question update .
Answer: Why do you have to update the item back to the list? You're not doing anything to the properties of the object on the server side are you?
Your edit method should look something like this:
    self.edit = function(item) {
        self.Product(item);

    };

and remove the following code nemesv said.
   self.Products.removeAll();
   self.Products(data.d); //Put the response in ObservableArray

My first post so be gentle ;)
Response to comment:
change your success to:
    success: function (data) {
          var product = ko.utils.arrayFirst(self.Products(), function(item) {
               return (item.Id == data.d.Id);
          });  // You could either update the product object with the new values from data.d or delete it and add a new product object.
          for (var p in product ) {
                product [p] = data.d[p];
          }

          self.Product(null);
          alert("Record Updated Successfully");
    },

Found a bug, it was replacing the observables with native values.
          for (var p in product ) {
                product [p](data.d[p]);
          }

I took the liberty of simplifying the code and removing everything that hasn't anything to do with the update function. The following code example should work. ( I used knockout 2.3.0 and jQuery 1.9.1)

Comment: :) i am updating the properties on server side and its working. the problem is its not populating with changed properties.
Comment: still no change in the table which is just above the update form . update value show after i refresh the page manually.
Comment: i have also update my question with screen shot . where you can see that when i click on update value are changed in db but that table still show old value.
Comment: Are your properties in the Product object observables?
Comment: Think i found the reason. Look at the bottom of my post.
Comment: I am new to knockout so not getting what you want to ask but i have pasted complete HTML of that page. GetAllProduct,Add,Delete working perfectly just facing issue with Update which is updating value in database successfully but html table its not show updated one .
Comment: product [p](data.d[p]);   is not a function ?
Comment: Response updated. I think the main problem is that when you're adding the objects to the self.Products observablearray you're just adding a anonymous object without any observable properties.


Problem with usb printer ports in Ubuntu 16.04

Question: I have 2 USB printers installed; they are assigned their ports /dev/usb/lp0 and /dev/usb/lp1.
But when I reboot my PC it often changes between them, for example, Printer 1 is assigned the port /dev/usb/lp0 before reboot and after I reboot it changes to the port /dev/usb/lp1.
Since each one has different paper settings this is a problem. How can I stop it from happening?
Comment: I don't know enough about the details to write a fully fleshed-out answer, but the keyword you might want to look into is "udev rules".
Answer: You may use udevrules, as @Henning said.
First find out some unique information for the printers by executing
$ sudo udevadm info -a /dev/usb/lp0
calling: info
.
.
    SUBSYSTEMS=="usb"
.
.
    ATTRS{idProduct}=="1763"
    ATTRS{idVendor}=="04a9"
    ATTRS{serial}=="8025E2"

(and equivalent for lp1)
This is just an example, but usually Vendor, Productand serialare sufficient. Now you can create a simple udev-rule to let udev create a unique name (link) for this printer when it is added. Create a file in /etc/udev/rules.d e.g. with sudo nano /etc/udev/rules.d/99-myprinters.rules to hold two lines like:
ACTION=="add", SUBSYSTEMS=="usb", KERNEL=="lp[0-9]*", ATTRS{idVendor}=="04a9", ATTRS{idProduct}=="1763", ATTRS{serial}=="8025E2", SYMLINK+="printer1"

Of course you have to replace the ids and serial by what udevadmreported. This means:
When a device is added (ACTION=ADD) that is an usb printer (SUBSYSTEMS=="usb", KERNEL=="lp[0-9]*") which matches vendor, product and serial number, add a symbolic link in /dev with the name printer1 (well, you may name the printer as you want, maybe something more intuitive).
Important: The name of the rules file has to end in .rules, otherwise it will be ignored. And you should respect the naming conventions for udev rules.
Sometimes printer drivers installation creates their own udev rules in /etc/udev/rules.d; just look at them for examples.
You can test this with sudo udevadm test <devicepath>, where <devicepath>has to be the full path reported by udevadm info, e.g. /devices/pci0000:00/0000:00:13.2/usb2/2-3/2-3.2/2-3.2:1.1/usbmisc/lp0.


Angular2 injected Router is undefined

Question: if I inject the router from @angular/router into a component and then use it, I get an error saying the cannot call navigateByUrl of undefined.
This is the component I use the router instance:
import { Component, OnInit } from '@angular/core';
import { UserAccountService } from '../service/user-account.service'
import { Response } from '@angular/http';
import * as jQuery from 'jquery';
import { Router } from '@angular/router';

@Component({
  selector: 'app-login',
  templateUrl: './login.component.html',
  styleUrls: ['./login.component.css']
})
export class LoginComponent implements OnInit {

  constructor(private userAccountService: UserAccountService,
              private appRouter: Router) { }

  public loginClicked(): void {
    this.userAccountService.Login(this.Email, this.Password).subscribe(this.loginCallback);
  }

  private loginCallback(data: any) {
    if(data.success) {
      localStorage.setItem('access_token', data.token);
      this.appRouter.navigateByUrl('/dashboard'); //-> error
    } else {
      [...]
    }
  }
}

The routes are defined inside the app module:
const appRoutes: Routes = [
  {  path: 'login', component: LoginComponent },
  { path: 'dashboard', component: DashboardComponent }
];

@NgModule({
  declarations: [
    AppComponent,
    LoginComponent,
    DashboardComponent
  ],
  imports: [
    BrowserModule,
    FormsModule,
    HttpModule,
    RouterModule.forRoot(appRoutes)
  ],
  providers: [UserAccountService],
  bootstrap: [AppComponent]
})

And inside index.html I define my

Did I forget anything? I have no clue on how to get it working correctly...
Comment: Where are you calling `loginCallback`? I guess context is very important here
Comment: ok, when adding the context I noticed I refer loginCallback and this inside the the userAccountsService.
Answer: You can use the arrow function to make sure you can still have a reference to this and it is LoginComponent instance:
....subscribe((data) => this.loginCallback(data));

Another option is use bind method like:
....subscribe(this.loginCallback.bind(this));

or in contructor:
this.loginCallback = this.loginCallback.bind(this);

One more option is using arrow function within your loginCallback:
private loginCallback = (data: any) => {
  ...
}

Angular2 injected Router is undefined


Unable to push local changes live using Git Push Heroku Master

Question: I'm new to GitHub and have gotten myself into a tangle. I've been successfully deploying code to a Heroku / Django app. However, my last commit was unsuccessful. This is my flow...
- Git add .
- Git commit -m "social media icons"
- Git push heroku master

The last command returns....
Fetching repository, done.
Everything up-to-date

Everything is not up to date. One thing I've discovered on my GitHub app is that I have 2 branches "production" and "master". Master was last updated Sept 8th. I've run a few commands including "git pull origin master" and "git push -f" based on other Stack answers. The latter did seem to push something but not the changes in local. Sorry, I'm trying to find my feet here!
Comment: which branch are you on? do a `git status` to see where you are since you are pushing to master.
Comment: @tayfun it says I'm on "branch production"
Answer: If you're on production branch then you will need to do
git push heroku production:master

Heroku will only deploy the master branch so this command is you pushing your local production branch into the master branch on the remote.
Answer: So you are on branch production but your other branch master is up to date. If you want to push the current branch you are on, you should explicitly say so:  git push heroku production.
I would highly advise you to try git, it's an excellent resource.


How to pipe through the output of hping3 from child to parent?

Question: I lately asked a question about how to call hping3 within a c program.
The solution provided works, but i now have another problem. The output from hping3 must be passed to the parent process, so i did the following.
Note that this is only the codesnippet, where i think the bug is within.
The following snippets runs inside a loop, where i iterate through a range of ip addresses, this is necessary to provide two different distribution strategies within my mpi program.
//Stick together the params
sprintf(params, "--scan %u %u.%u.%u.%u -V", *(portarray + i), (iterator & 0xFF000000)>>24, (iterator & 0x00FF0000)>>16, (iterator & 0x0000FF00)>>8, (iterator & 0x000000FF));
            //Pipe and check status
            if(pipe(pipes)==-1){
               perror("Error piping");
            }
            //Fork and check status
            pid=fork();
            if(pid == -1){
               perror("Error forking");
            } else if(pid > 0){
               //Parent does not write
               close(pipes[1]);
               //Save stdout from pipe
               nbytes = read(pipes[0], buffer, sizeof(buffer));
               //Parent, wait for child
               waitpid(pid, &status, 0);
               //Print out pipe
               printf("hping3: (%.*s)\n", nbytes, buffer);
               wait(NULL);
               close(pipes[0]);
            } else {
               //Child does not read
               close(pipes[0]);
               //Map stdout and stderr to write pipe-end
               dup2(pipes[1], 1);
               dup2(pipes[1], 2);
               //Child, exec hping with params
               execl("sudo /usr/sbin/hping3","sudo /usr/sbin/hping3",params,NULL);
               close(pipes[1]);
               //Exit child to prevent fork-bomb
               return 0;
            }
            //Sleep for specified delaytime
            sleep((unsigned int)delay);

I can't figure out where the problem is.
Output is the following (in a loop of course):
hping3()

The hping3 program prints out to stdout and stderr, i tested it on the shell via output redirection to a file.
Answer: How is buffer defined? Did you ever check the value of nbytes? Are you sure that hping is being executed? I'd try with the following:
int buffsize  = 100;
char * buffer = malloc(buffsize);

if (pid == -1) {
   perror("Error forking");
} else if (pid > 0) {
   //Parent does not write
   close(pipes[1]);
   // I'd first wait for the child to finish.
   waitpid(pid, &status, 0);
   // Save stdout from pipe
   // recall that sizeof(buffer) != buffsize when malloc'ed.
   int count = 0;
   while((nbytes = read(pipes[0], buffer+count, buffsize-count) != -1) count += nbytes;
   //Print out pipe
   printf("hping3: (%.*s)\n", nbytes, buffer);
   wait(NULL);
   close(pipes[0]);
} else {
   //Child does not read
   close(pipes[0]);
   //Map stdout and stderr to write pipe-end
   dup2(pipes[1],1);
   dup2(pipes[1],2);
   // Close pipes[1]
   close(pipes[1]);
   //Child, exec hping with params
   if (execl("sudo /usr/sbin/hping3","sudo /usr/sbin/hping3",params,NULL) == -1)
      perror("execl error");
   //Exit child to prevent fork-bomb
   return 0;
}

Comment: buffer is defined as char buffer[4096]. nbytes is defined as int nbytes and initialized with 0 before the main loop. hping3 is being executed know this because of a parameter i forgot in a earlier version of this program
Comment: did you try the code (waitpid first then read)? does it work?
Comment: Sry was not able to do that, the last days where really stressful.
Comment: Finally had time to test it and unfortunally it is not working for me. The execution got stuck at the execl statement. hping3 was actually not executed.


Fetch to Express returning Old Data

Question: When running a fetch request to a node express server, it returns old data (that was previously returned from the same endpoint). This happens sporadically, but more often than not.
I have disabled the Cache-Control in the fetch header, but that did not work.
The Express server is running on a Windows Server, through PM2, which is accessed through a Reverse Proxy in IIS (pointing to the local pm2 host, on port 5000) with an SSL certificate attached to the domain.
This does NOT happen when the backend is hosted through the localhost on my machine (NOT the server).
My fetch request is as follows:
fetch(URL, {
     headers: {'Cache-Control':'no-cache'}
}).then(r=>r.json())
  .then(json=>...)

Does anyone have any idea on what's causing this? Is there a preference in Windows Server or IIS that I need to change? Or is there something in PM2?
Comment: Does this answer your question? [What is the difference between no-cache and no-store in Cache-control?](https://stackoverflow.com/questions/7573354/what-is-the-difference-between-no-cache-and-no-store-in-cache-control)
Comment: @KrzysztofKrzeszewski afraid not, I switched it over to no-store, and the same issue happens. I think it's something to do with Windows Server, IIS or PM2, but unsure as of right now.
Comment: So I've done some digging, and it turns out it has to do with the express NodeJS backend running on Windows Server 2019. If anybody knows current issues regarding reverse proxies, IIS and Node on Windows Server and returning requests, that would be great.
Answer: I had to modify the Cache-Control header in the ISS Reverse Proxy.
I changed it to no-store as recommended by @KrysztofKrzeszewski, and all is working now.

Fetch to Express returning Old Data


Kodi package problems after upgrade from 13.10 to 14.04: libsdl2 not found

Question: After my HTPC system upgrade from Ubuntu 13.10 to 14.04 I can't seem to install Kodi.
I run
sudo apt-add-repository ppa:team-xbmc/ppa
sudo apt-get update
sudo apt-get install kodi kodi-bin

And get:
The following packages have unmet dependencies:
 kodi-bin : Depends: libsdl2-2.0-0 (>= 2.0.0) but it is not going to be installed
E: Unable to correct problems, you have held broken packages.

I had a few PPA's insatalled on old stystem and removed them all from sources list. I also ppa-purge the ream-xbmc's ppa and re added it. Some other ppa's I removed from sources list, as ppa-purgeing them failed.  The old system had XBMC running without issues. The upgrade was smooth, and had no errors.
I see some other people had same problem, but solved by manually installing a deb.  This makes me think my apt is very confused, and I would rather not break my setup further.
This system was installed using an older version of this guide. I additionally installed Gnome for occasional web browsing.
How do I go about debugging this package problem? What would make my system not know about libsdl2-dev? Did I find a bug in the team-xbmc ppa?
Some more info:
$ apt-cache policy libsdl2-dev
libsdl2-dev:
  Installed: (none)
  Candidate: 2.0.2+dfsg1-3ubuntu1.1
  Version table:
     2.0.2+dfsg1-3ubuntu1.1 0
        500 http://za.archive.ubuntu.com/ubuntu/ trusty-updates/universe amd64 Packages
     2.0.2+dfsg1-3ubuntu1 0
        500 http://za.archive.ubuntu.com/ubuntu/ trusty/universe amd64 Packages

$ dpkg -S /usr/lib/x86_64-linux-gnu/libSDL*
libsdl1.2debian:amd64: /usr/lib/x86_64-linux-gnu/libSDL-1.2.so.0
libsdl1.2debian:amd64: /usr/lib/x86_64-linux-gnu/libSDL-1.2.so.0.11.4
libsdl-image1.2:amd64: /usr/lib/x86_64-linux-gnu/libSDL_image-1.2.so.0
libsdl-image1.2:amd64: /usr/lib/x86_64-linux-gnu/libSDL_image-1.2.so.0.8.4

Comment: The package is available for Trusty. Force the install with `sudo apt-get install libsdl2-2.0-0`
Comment: @A.B. That gives me next dependency problem `The following packages have unmet dependencies:
 libsdl2-2.0-0 : Depends: libwayland-egl1-mesa (>= 10.0.2) or
                          libwayland-egl1` I actually want to fix the root cause of this package problem. Why do I have to force install anything?
Comment: ck. what version of libwayland-egl1-mesa is installed, maybe you have the lts version? `apt-cache policy libwayland-egl1-mesa*` &  ck. what mesa you are using, 14.04 orig.  or one of the lts versions.
Comment: @doug http://paste.ubuntu.com/11791594/ doesn't look like I have any `libwayland` installed.
Comment: What release/flavor are you actually running? Ubuntu or Ubuntu-Gnome would require some version of libwayland-egl1-mesa to be installed
Comment: I am running Ubuntu server 14.04, and installed Gnome afterwards.
Answer: I think I found the problem, as Kodi is now installing correctly:
First I found all the packages that were still hanging around from saucy by running
dpkg --list | grep saucy

One by one I removed them all using apt-get remove <packagename>.  (I suspect these were old packages that were installed via some weird ppa when I installed gnome.)
After removing all the saucy packages, I ran apt-get autoremove to cleanup the rest of the packages.  Then I ran into what seems to be a libgl1-mesa-dri bug.
dpkg: error processing archive /var/cache/apt/archives/libgl1-mesa-dri_10.1.3-0ubuntu0.4_amd64.deb (--unpack):
 trying to overwrite shared '/etc/drirc', which is different from other instances of package libgl1-mesa-dri:amd64

Luckily simple workaround of sudo mv /etc/drirc /etc/drirc.bak2 fixed that and I could install Kodi again withouth further trouble.
Answer: Try running this
sudo apt-get install -f
sudo dpkg --configure -a
sudo apt-get clean
sudo apt-get update

This should clean up any broken packages.
Then you should try this again
sudo apt-get install kodi kodi-bin

Hope this helps
Comment: I ran those commands, but still get same error. It didn't look like there were any broken packages.
Comment: And why twice `sudo apt-get update`?
Comment: hmm thats strange I dont know at the moment ill keep thinking on it tho @Diedrik and i didnt notice that i put 2 apt-get update sorry I'm tired.
Answer: I had the same problem after upgrading from 15.04 to 15.10. The solution I found here: Ubuntu Forums: broken package libsdl2

See what packages are not in the cleanly installed state (I had a lot!):
dpkg -l|sed -nr '/^.[^in]/s/^(.{78}).*/\1/p'

Add back the missing PPA, in my case the one from Kodi.

Bring every program up to the current levels and install the latest kernel:
sudo apt-get dist-upgrade

After that, Kodi could be installed again in my case; Then either continue to use the PPA or use ppa-purge on it.

In the future purge all PPAs before upgrading Ubuntu releases!


How should I pretreat painted plasterboard before gluing fiber cement sheet over it

Question: I'm going to glue (and nail) cement tile underlay sheet to a painted plasterboard wall.
The paint seems to have decent adherence, should I do anything before gluing?
Comment: I'm thinking of doing something similar. Can you recommend which kind of adhesive to use?
Answer: I'd sand it lightly and wash it thoroughly afterwards to get any particles off, you'll get better and longer-lasting adherence.


Process dynamic email addresses using python

Question: I need to do the following and I was wondering if anyone has done something similar, and if so what they did.
I need to write a program that will handle incoming emails for different clients, process them, and then depending on the email address, do something (add to database, reply, etc).
The thing that makes this a little more challenging is that the email addresses aren't static they are dynamic. For example. The emails would be something like this.   email@example.com . The emails are grouped by client using a dynamic subdomain in this example it would be 'dynamic-subdomain1'. A client would have their own subdomain that is assigned to them. Each client can create their own email address under their subdomain, and assign an event to that email. These email addresses and subdomains can change all of the time, new ones added, old ones removed, etc.
So for example if an email comes in for the email 'firstname.lastname@example.com' then I would need to look up in the database to find out which client is assigned the 'dynamic-subdomain1' subdomain and then look to see which event maps to the email address of 'dynamic-email1'  and then execute that event. I have the event processing already, I'm just not sure how to map the email addresses to the event.
Since the email addresses are dynamic, it would be a real pain to handle this with file based configuration files, it would be nice to look up in a database instead. I did some research and I found some projects that do something similar but not exactly. The closest that I found is Zed Shaw's Lamson project: http://lamsonproject.org
More background:

I'm using python, django, linux, mysql, memcached currently.

Questions:

Has anyone used Lamson to do what I'm looking to do, how did you like it?
Is there any other projects that do something similar, maybe in a different language besides python?
How would I setup my DNS MX record to handle something like this?

Thanks for your help.
Update:
I did some more research on the google app engine suggestion and it might work but I would need to change too many things and it would add too many moving parts. I would also need a catch all emailer forwarder, anyone know of any good cheap ones? I prefer to deploy on system that handles all email. It looks like people have used postfix listening on port 25 and forwarding requests to lamson. This seems reasonable, I'm going to try it out and see how it goes. I'll update with my results.
Update 2:
I did some more research and I found a couple of websites that do something like this for me, so I'm going to look at them next.
http://mailgun.net
http://www.emailyak.com
Answer: I've done some work on a couple projects using dynamic email addresses, but never with dynamic subdomains at the same time. My thoughts on your questions:

I've never used Lamson, so I can't comment on that.
I usually use App Engine's API to receive and handle incoming messages, and it works quite well. You could easily turn each received message into a basic POST request on your own server with e.g. To, From, Subject, and Message fields and handle those with standard django.
One downside with GAE email is having to use *@yourappname.appspotmail.com, but you could get around that by setting up a catch-all email forwarder for *@yourdomain.com to direct everything to firstname.lastname@example.com. That would let you receive the messages on the custom domain and handle them with GAE.
The other issue/benefit with GAE is using Google's servers instead of your own (at least for the email bit).
For the subdomain issue, you could try setting up wildcard DNS for the MX records, which (in theory) would direct all mail sent to any subdomain to the same server(s). This would enable you to receive email on all subdomains (for better or worse--look out for spam!)
Comment: Yeah, I thought about the "regular" email issue, too. Maybe the wildcard record could point subdomains to e.g. `app_mail.mydomain.com` with the catch-all on that (instead of on the bare domain)? If the subdomain issue gets too complicated, it might be worth considering an alternate syntax, like `firstname.lastname@example.com` if that makes things easier.
Comment: Thanks for the App Engine suggestion, I thought about app engine, but I wasn't sure how to do it with the appspotmail.com email address restriction, I'll have to try it out for the forward and see if it will work. The one problem is that my normal emails firstname.lastname@example.com would also go to appengine as well. It doesn't look like there is a rate limit for incoming email, which is good as well.
Comment: The way the app works now it has heavy use of subdomains, but I'll see if I can work around that to try your email@example.com approach, it does make things a little cleaner, but I'm guessing I might have to do email@example.com or something similar so that my regular @mydomain.com emails aren't sent to the same MX server as the automated ones. Thanks for the suggestion.
Answer: For lamson, have you tried something as simple as:
@route("(address)@(subdomain).(host)", address=".+", subdomain="[^\.]+")
def START(message, address=None, subdomain=None, host=None):
    ....


Grub gives messages about the boot sector being used by other software. What should I do?

Question: This only happens with one of my computers. It is an elderly laptop that has had a long and varied history with several operating systems, but in its retirement it is acting as a server for my home network using Ubuntu 12.04. It is a single-boot system, there are no other systems installed.
Every so often, whenever there is a grub upgrade, I notice a message like this:
Setting up grub-common (1.99-21ubuntu3.4) ...
Installing new version of config file /etc/grub.d/00_header ...
Setting up grub2-common (1.99-21ubuntu3.4) ...
Setting up grub-pc-bin (1.99-21ubuntu3.4) ...
Setting up grub-pc (1.99-21ubuntu3.4) ...
/usr/sbin/grub-setup: warn: Sector 32 is already in use by FlexNet; avoiding it.  This software may cause boot or other problems in future.  Please ask its authors not to store data in the boot track.
Installation finished. No error reported.

Should I be worried about this? What (if anything) should I do about it?
Comment: FYI, "FlexNet" is written by Flexera software to keep track of licenses.
Comment: @user10089632 not sure what your comment is aimed at? The answer you linked is to a totally different question. Maybe you need to talk to Google, but otherwise I can't help you since I have no idea what search terms you were using.
Comment: I don't know when google is planning on showing the most [upvoted answer](https://askubuntu.com/questions/88384/how-can-i-repair-grub-how-to-get-ubuntu-back-after-installing-windows#88432) first in its search results...
Comment: Thanks a lot! 2020 and the same issues.... QUESTION: I need to do the procedure via ssh. Is it mandatory not to run the drive where the correction is applied? Why is it necessary to have an external boot media? What would be wrong if I just do the overwrite in situ? Please give me some hints!
Comment: @opinion_no9 Having external boot media means you are not dependent on the boot sector of the computer's hard drive, so that you can edit it without crashing the machine. This is the kind of job where I think you have to have physical access to the box, or risk bricking it. My own answer provides a few links that may help you.
Comment: @Bobble Thanks a lot for your comment!  Since the boot sector is absolutely not in use while the machine operates I can not see a risk.   Meanwhile I tried to remove "FlexNet" via ssh: Works perfect!!  Just do two steps: dd into "32" as described +  sudo grub-install /dev/yourdisk  + reboot to verify.    Problem solved!   That simple!  Thanks to you all contributing the sophisticated solutions ...
Comment: @opinion_no9 Nice, glad you solved it. The risk comes if you botch it, you can easily end up with a mc that cannot be booted. Having a boot disk makes things a lot safer.
Answer: It's not a big deal since there is no error reported so just warning.
But, if you wish to get rid of this, you need to wipe sector 32. To do this you have many choices:
a. Wiping the whole hard disk;
b. writing zeros to Whole sectors in your MBR and reinstall your grub;
c. Writing zeros to sector 32 in your MBR (that's what we'll do here).
To do that follow the following steps:

Backup your MBR:
sudo dd if=/dev/sda of=~/first_63_sectors bs=512 count=63

zero your sector number 32:
sudo dd if=/dev/zero of=/dev/sda bs=512 count=1 seek=32

chroot and reinstall grub:
Here "/media" should be whatever your chosen mount point is. Some step-by-step instructions use "/mnt" rather than "/media".
sudo mount /dev/sda* /media/sda*

sudo mount --bind /dev /media/sda*/dev

sudo mount --bind /proc /media/sda*/proc

sudo mount --bind /sys /media/sda*/sys

sudo chroot /media/sda*

PS: replace * by the appropriate number of your hdd
Now update your grub:
sudo update-grub

Note: You are not obliged to these steps, since its not an error that may affect your system.
Comment: Thanks maythux. Further info about this in my own answer (especially what to do when things go wrong...)
Comment: I think you are right, 'leave well alone' was an option here, but at the same time I figure the warning is there because in the future it *will* cause a problem, so it's better to get rid of it.
Comment: You are welcome and ive read your answer its great u deserve +1
Comment: This didn't worked for me. I tried even [this](http://pissedoffadmins.com/general/usrsbingrub2-bios-setup-warning-sector-32-is-already-in-use-by-the-program-flexnet-avoiding-it-this-software-may-cause-boot-or-other-problems-in-future-please-ask-its-authors-not-to-store.html). I'm still greet with the grub bootloader.
Comment: Thanks, but I didn't do the whole procedure 3. I only did "sudo update-grub" in procedure 3 after 1 and 2. Is it necessary " sudo mount ..."?
Comment: the chroot in step 3 is only necessary if you are not running the system live (eg. you are running from a rescue disk) -- I had three sectors involved and was able to do this on the system directly (no chroot).
Answer: I found a couple of useful links that explain what the message is about, and how to clean out the boot sectors on the disk.
This thread gives a very good explanation of the problem.
This thread gives a nice easy cookbook recipe for cleaning things up.
The cookbook worked for me, although I made a mess of the chrooting bit... (see below)
I am lucky in that my computer is single-boot and I have no plans EVER to re-install Windows. But it seems that if you have a dual-boot Windows system with software that uses FlexNet or similar software, you can expect to have regular problems. Also I think some Windows viruses may use this part of the disk. The first thread discussion offers a solution for Ubuntu users, to install an app called boot-repair on your live-CD USB booter.
I also found the boot-repair program referred to above invaluable when things go wrong. IMHO this is so useful it should be on the Live CD by default. See this link.
Comment: Thanks a lot for your comment!  The first contirbution in the first mentioned article is great - but I would NEVER EVER install such a dodgy "app" on a machine! Snakeoil and uncertain sources. Never!  Dual Boot is not the issue. Adobe is the issue. Can not always change that .... Meanwhile I  removed "FlexNet" even via ssh: Works perfect!! Just do two steps: dd zeros into "32" as described above + sudo grub-install /dev/yourdisk + reboot to verify. Problem solved! That simple!
Answer: Less CLI typing with live DVD/USB
Here is a way of doing the same with less command line typing, using a live DVD or a live USB.

Boot into a live session (= select trying out (X)Ubuntu).

Use the lsblk command to show all drive partitions.
NAME   MAJ:MIN RM   SIZE RO TYPE MOUNTPOINT
sda      8:0    0 298.1G  0 disk
├─sda1   8:1    0   512M  0 part /boot
├─sda2   8:2    0   4.5G  0 part [SWAP]
├─sda3   8:3    0    44G  0 part /
└─sda4   8:4    0 249.1G  0 part /home
sr0     11:0    1  1024M  0 rom

Make sure you target the affected drive (here sda).

Remove FlexNet from the affected drive (here /dev/sda), using the sector number reported by GRUB (here sector 32):
$ sudo dd if=/dev/zero of=/dev/sda bs=512 count=1 seek=32

There is no need to backup this usually empty part of the extended boot record (EBR).

Now, mount the partition of the affected drive which is normally used for booting (here /dev/sda1).
$ sudo mount /dev/sda1 /mnt

Finally, reinstall GRUB on the affected drive:
$ sudo grub-install --boot-directory=/mnt /dev/sda

GRUB should now install without any warnings.

You are now safe to reboot from the disinfected hard drive.
Comment: great, Thanks a lot!  2020 and the same issues....
QUESTION:
I need to do the procedure via ssh. Is it mandatory not to run the drive where the correction is applied? Why is it necessary to have an external boot media? What would be wrong if I just do the overwrite in situ?  Please give me some hints!
Comment: @Bobble Thanks a lot for your comment! Since the boot sector is absolutely not in use while the machine operates I can not see a risk. Meanwhile I tried to remove "FlexNet" via ssh: Works perfect!! Just do two steps: dd into "32" as described + sudo grub-install /dev/yourdisk + reboot to verify. Problem solved! That simple! Thanks to you all contributing the sophisticated solutions ...
Comment: @opinion_no9 I used an external boot medium at the time because I was installing a used hard drive to replace a smaller boot drive. You can read more about this and removing _FlexNet_ in my article [_Same PC, New HD_](https://hamwaves.com/same_pc.new_hd/en/index.html)


What is the import process in Thunderbird for backup.pst files

Question: I am not able to restore my previous mail backup data file backup.pst.
kindly help on the same.
Answer: Mozillazine Article says:

There are several open source utilities to convert .pst files to mbox
  files such as readpst , libpst and Outport . Thunderbird uses a
  separate mbox file for each folder to store all of the messages for
  that folder. None of those utilities seem to be under active
  development and they only support some of the versions of .pst files.
  You can use the ImportExporttools extension to import the mbox files.

readpst is in the repos, but lacking a .pst file I can't try it
Answer: I had some success using readpst.
sudo apt-get install readpst
mkdir pst-export
readpst -D -M -b -o pst-export archive.pst
find . -type f ! -iname '*.eml' -exec rename 's/([0-9]+)$/$1.eml/' {} \;

Then import the .eml files into Thunderbird. I suggest using the ImportExportTools plugin.
Answer: the purpose of this mini script

find . -type f ! -iname '*.eml' -exec rename 's/([0-9]+)$/$1.eml/' {}
  \;

is to rename all mbox files with the name of the directory in where they are
I use this method
convert

readpst  -k -D -b -o [~/target/directory] [SourceFile.pst]

it will create files with the correct filename directly
import
create a subfolder in the "local folders"
right click on it and use the pluging ImportExportTool

"import mbox files"
"select a directory where searching the mbox files to import (also in subdirectories)


Error Converting Datatype nvarchar to int in SSRS for multivalued Parameter

Question: I have a parameter Client in the report which takes Multivalues.
When i run the value for one client, it's working fine, but when i include more than 1 client it's giving the error like:

"Error Converting Datatype nvarchar to int in SSRS for multivalued Parameter"

Here is the stored procedure which is giving the data based on the client parameter
<code>Create PROCEDURE SampleLead
@InvClientId int
AS
begin

 SELECT [SourceSystemId]
  ,[SourceLeadId]
  ,[FirstName]
  ,[LastName]
  ,[Title]
  ,[TitleType]
  ,[Role]
  ,[CustomerName]
  ,[Address1]
  ,[Address2]
  ,[City]
  ,[State]
  ,[ZipCode]
  ,[Country]
  ,[InvClientId]
  ,[Campaign]
  ,[Email]
  ,[Phone]
  ,[InvUserId]
  ,[RevenueRangeId]
  ,[EmployeeRangeId]
  ,[Industry]
  ,[SICCode]
  ,[NAICSCode]
  ,[DUNSNo]
  ,[CreatedDate]
  ,[ModifiedDate]
  ,[LeadStatus]
 FROM [CRMIntegration].[dbo].[Lead]
 Where InvClientid in (@invClientID)

END
GO
</code>
invClientId is declared as int in the source table
And SSRS parameter i have set the datatype as int.
Can you help me why it is not working for multiple values but working when i select single value?
Answer: It cannot be done based on your stored procedure.
Refer to ..
Example of passing multi values from SSRS to Stored Procedure


How to carry over variable from pytest fixture to an actual test?

Question: I have a pytest that rely on setup/teardown fixture to create/delete a kinesis stream:
<code>@pytest.fixture()
def clean_up_kinesis_test():
    stream_name = uuid.uuid4().hex
    api_utils.create_kinesis_stream('us-east-1', stream_name, 1)
    assert active
    yield
    api_utils.delete_kinesis_stream('us-east-1', stream_name)

@pytest.mark.usefixtures("clean_up_kinesis_test")
def test_func1():
    # Use the stream_name from the fixture to do further testing

@pytest.mark.usefixtures("clean_up_kinesis_test")
def test_func2():
    # Use the stream_name from the fixture to do further testing
</code>
Is there a way I can pass the stream_name from the fixture to the actual test_func1 and test_func2?
I cannot use global variable as each test will need to have their own stream to do testing.
Comment: Yield **a value**, drop the unnecessary `mark` line and add the fixture's name to the arguments of the test function.
Answer: Yield the value from the test fixture and pass the fixture as an argument into each test.
<code>import pytest
import uuid

@pytest.fixture()
def clean_up_kinesis_test():
    stream_name = uuid.uuid4().hex
    yield stream_name

def test_func1(clean_up_kinesis_test):
    print(clean_up_kinesis_test)

def test_func2(clean_up_kinesis_test):
    print(clean_up_kinesis_test)
</code>


How to find shell environment variable

Question: Is there anyway to find where to define the linux environment variable? When I print the environment variable using:
env

the output is:
PATH=/home/local/apache-maven-3.3.9/bin:/home/hldev/software/sbt:/home/local/jdk1.8.0_111/bin:/bin:/home/local/gradle-3.5.1/bin:/home/local/node-v6.9.2/bin:/home/hldev/bin:/home/hldev/.local/bin:/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin:/usr/games:/usr/local/games:/snap/bin:/opt/node-v8.9.4-linux-x64/bin:/home/local/go/bin:/home/local/gradle-5.3/bin

How to find where to define the /home/local/gradle-3.5.1/bin and make /home/local/gradle-5.3/bin works.I define the /home/local/gradle-5.3/bin in bash_profile,but I could not find where to define /home/local/gradle-3.5.1/bin environment variable.Here is the path I aready checked:
/etc/profile
/root/.bash_profile
/home/dolphin/.bashrc
/home/dolphin/.bash_profile

PS: the OS is:Ubuntu 16.04 LTS
Comment: [How to determine where an environment variable came from?](https://unix.stackexchange.com/q/813/56041), [How to find where an environment variable is set](https://stackoverflow.com/q/8058487/608639) and friends.
Answer: Other than using find and grep, there isn't much you can do to discover where each variable comes from.
Knowing that it is indeed an environment variable, I would attempt focusing the search in /etc/ and your home directory. Replace var with the appropriate variable you're searching for:
$ grep -r var /etc/*
To print all the environment variables set in your shell, you can do the following:
$ printenv | less
Some places where to look for environment variables:
System wide

/etc/environment: specifically meant for environment variables
/etc/env.d/*: environment variables, split in multiple files
/etc/profile: all types of initialization scripts
/etc/profile.d/*: initialization scripts
/etc/bashrc, /etc/bash.bashrc: meant for functions and aliases

User specific

~/.bash_profile: initialization for login (bash-)shells
~/.bashrc: initialization for all interactive (bash-)shells
~/.profile: used for all shells
~/.cshrc, ~/.zshrc, ~/.tcshrc: similar for non-bash shells
Comment: I found it on ~/.profile one by one by your tips,thank you.I already using find or grep command but it is too slow.@Paradox
Answer: Google tells me that there may be a configuration file at:
/etc/profile.d/gradle.sh

Answer: Under bash shell:

To list all the environment variables, use the command " env " (or "
printenv ").
To reference a variable, use $varname , with a prefix '$' (Windows uses %varname% ).
To print the value of a particular variable, use the command " echo
$varname ".

How to find shell environment variable


Represent shape as particles

Question: Input: Triangles which make up an arbitrary shape. Each triangle is represented by 3 3D points.
Output: A set of particles which fills up the inside of the object (see image).

I have read the description made by GPU-Gems, and tried to implement the proposed solution that don't make the computations on the GPU. I have tried to take each triangle one at a time and see if they intersect with lines, and if so store the z-value which I later used to generate particles. This gave bad results, and in theory it is possible for a line to intersect with a lone point which would cause a bug.
Can anyone tell me how to easily on the CPU side create a set of particles that represent a shape? Where the shape is defined as a set of triangles.
I prefer a solution that is simple and works well rather than an efficient solution that can have bugs.
Edit: I re-checked my code, and I found that I was not sorting the z-value arrays correctly like I thought I did, after fixing this I got a good result! If anyone still wants to answer this question that is ok, but I consider my problem to be solved now.
Answer: Solution: Check for the minimum x,y,z value for all points. Add these values multiplied by (-1) to all points in order to guarantee that all points are not negative. Then take the largest point and subtract with the minimum point (max and minimum x y z) in order to get a cube-like bound for the object.
Then divide this cube by an arbitrary size constant representing the radius of each particle. Now you should have a 2D array for z-values, such that for any x, y position you can quickly store z-values that you find intersecting lines.
For each triangle in the mesh, check all possible that have a large or small enough x-y value for intersections with a line going through the whole cube. If there is an intersection, save the z-value in the x-y array for z-values.
Lastly loop through each possible z-values in the imaginary cube and check if it has an odd number of z-value hits before the current z-value. If that is the case, then we know that there is a particle here. Don't forget to add the minimum x,y,z values that we added in the beginning in order to make the particles have the correct positions again.

Represent shape as particles


PDF Arranger trying to export pages to make a new PDF of just the first few pages

Question: I try to export selection to a new single file and it gives me the error message
"Use pikepdf.Pdf.pages interface to copy pages from one PDF to another"
trying to use the alternative pdfsam gives me this output
$ pdfsam Graphics Device initialization failed for :  es2, sw Error initializing QuantumRenderer: no suitable pipeline found java.lang.RuntimeException: java.lang.RuntimeException: Error initializing QuantumRenderer: no suitable pipeline found

Answer: Export all the pages that you want to reuse as individual single-page PDFs, then import these individual pages back into a new PDF Arranger window and save them all together as a new multi-page PDF document.

Click the first page that you want to export, then use the Ctrl key and the left mouse button to select the other pages that you want to export one by one until you have selected all of the pages that you want to export.

Click the three horizontal lines Main Menu icon ≡ in PDF Arranger and select Export -> Export Selection to Individual Files. If you have selected five pages then this will export each of these pages to an individual PDF file.

Import the single page PDFs that you saved into a new PDF Arranger window. Click the three horizontal lines Main Menu icon ≡ and select the Save as option to save all the pages that you imported into PDF Arranger as a new multi-page PDF document.

The PDF Split and Merge application (pdfsam) from the default Ubuntu repositories can also be used to extract a selection of pages as a new PDF document. pdfsam can be installed by sudo apt install pdfsam in all currently supported versions of Ubuntu. The Extract tool can be used to specify a list of pages separated by a commas used as delimiter characters, and the whole list of pages can be saved as a new PDF document by clicking the  ▶  Run  button in the lower left corner as shown in the screenshot.
Comment: I tried export selection to individual files it gives me the same error message
Comment: @ubuntunoob The PDF Split and Merge application (*pdfsam*) from the default Ubuntu repositories can also be used to extract a selection of pages as a new PDF document. I edited my answer and added the instructions for using it.
Comment: `$ pdfsam
Graphics Device initialization failed for :  es2, sw
Error initializing QuantumRenderer: no suitable pipeline found
java.lang.RuntimeException: java.lang.RuntimeException: Error initializing QuantumRenderer: no suitable pipeline found
 at`
Comment: @ubuntunoob Your Ubuntu definitely has a software issue. All of the relevant information about this software issue should be copied to your question, so that all Ask Ubuntu users can read it.
Comment: which info would that be?
Comment: The third comment below this answer.


Swift - Merge two arrays whilst removing keys duplicates and adding array values together

Question: I have two arrays that look something like the below example. What I would like to do is merge the two together. If their keys are equal remove the duplicate and add both of their values together.
Any help is greatly appreciated, many thanks!!
Current Code:
struct Example: Codable {
    var key: String
    var value: Int
}

var first: [Example] = []
var second: [Example] = []

first.append(Example(key: "1", value: 10))
first.append(Example(key: "2", value: 10))
first.append(Example(key: "3", value: 10))

second.append(Example(key: "2", value: 10))
second.append(Example(key: "3", value: 10))
second.append(Example(key: "4", value: 10))

let merged = Array(Dictionary([first, second].joined().map { ($0.key, $0)}, uniquingKeysWith: { $1 }).values)

Currently Prints
Example(key: "3", value: 10)
Example(key: "1", value: 10)
Example(key: "2", value: 10)
Example(key: "4", value: 10)

What I would like do to:
Example(key: "3", value: 20)
Example(key: "1", value: 10)
Example(key: "2", value: 20)
Example(key: "4", value: 10)

Answer: You are nearly there!
In the uniqueKeysWith parameter, you should create a new Example that contains the same key, and the sum of the two parameters' values:
let merged = Array(Dictionary([first, second].joined().map { ($0.key, $0)}, uniquingKeysWith: { Example(key: $0.key, value: $0.value + $1.value) }).values)

Comment: Works perfectly! Thank you so much!!


jQuery drop-down menu doesn't appear

Question: guys,
I'm JavaScript/jQuery rookie and now I'm learning the basis using a Udemy video tutorial, which I bought recently. Everything so far was good (except the lector thinks that the student already has a strong OOP knowledge?!).
Unfortunately I can't handle my last task. I checked for more than two hours for an error and never found it. Here's the code which I merged into one file to make it easier for you to track everything. The goal is to hover the mouse on the link "You have logged in as:" and the hidden menu
"My account
Profile
Settings
Log out"
to appear. Without jQuery the menu is on it's place, but obviously there's something wrong within the jQuery code.
Any help will be accepted with great regard!
<!DOCTYPE html>

jQuery

You have logged in as:

My account

Profile

Settings

Log out

Answer: You have to use .next() and not .find() since your .submenu is not a child of the li, but a sibling.
$(this).parent().next('.submenu');

Note

 should never be a direct child of another

Demo

$(document).ready(function() {
    $('[data-trigger="dropdown"]').on('mouseenter', function() {
      var submenu = $(this).parent().next('.submenu');
      submenu.addClass('active');

    });
});
h2 {
  display: inline-block;
}

.profile-menu {
  float: right;
  display: block;
  margin-top: 20px;
  margin-right: 20px;
  list-style-type: none;
}

.submenu {
  list-style-type: none;
  padding: 0px;
  border: 1px solid #aadd23;
  background: beige;
  margin-top: 10px;
  box-shadow: 7px 3px 5px rgba(0, 0, 0, .3);
  position: absolute;
  right: 10px;
  display: none;
}

.submenu.active {
  display: block;
}

.submenu a {
  text-decoration: none;
  padding: 10px 30px;
  display: block;
  color: #345;
  text-shadow: none;
  font-weight: 600;
  letter-spacing: 2px;
  width: 300px;
}

.submenu a:hover {
  background: #eee;
}

jQuery

You have logged in as:

My account

Profile

Settings

Log out

Correct html

$(document).ready(function() {
  $('[data-trigger="dropdown"]').on('mouseenter', function() {
    var submenu = $(this).next('.submenu');
    submenu.addClass('active');

  });
});
h2 {
  display: inline-block;
}

.profile-menu {
  float: right;
  display: block;
  margin-top: 20px;
  margin-right: 20px;
  list-style-type: none;
}

.submenu {
  list-style-type: none;
  padding: 0px;
  border: 1px solid #aadd23;
  background: beige;
  margin-top: 10px;
  box-shadow: 7px 3px 5px rgba(0, 0, 0, .3);
  position: absolute;
  right: 10px;
  display: none;
}

.submenu.active {
  display: block;
}

.submenu a {
  text-decoration: none;
  padding: 10px 30px;
  display: block;
  color: #345;
  text-shadow: none;
  font-weight: 600;
  letter-spacing: 2px;
  width: 300px;
}

.submenu a:hover {
  background: #eee;
}

jQuery

You have logged in as:

My account

Profile

Settings

Log out

Comment: Thanks a lot, m-r Andersen.
It runs now! Obviously I have to learn much more about jQuery - it really differs from Vanilla JS. Moreover I realize now that my error is in HTML code - I haven't put the closing li tag at the proper place and in reality those elements have been changed themselves to siblings :(   Always my empty haste...
After I fixed my HTML mistake, the first case - with .find() works too.
Anyway, what a shame for me! Such a stupid little error.
I was thinking I know HTML 5... ;)
Comment: @php2webdeveloper No problem, happy to help and remember that there is no shame of being knew to something or need help

jQuery drop-down menu doesn't appear


Why are login forms centered?

Question: Why are login forms always centered on the screen? Most horizontally, some vertically also. Sites like Apple/Amazon/Adobe/Microsoft/Google/PayPal/Instagram/Twitter etc. are all centered! Is this an undocumented best practice everyone unanimously decided to use?

download bmml source – Wireframes created with Balsamiq Mockups
Obviously it's most aesthetically pleasing, but is there any other reasons why?
Edit: Many of these sites do not support mobile either, so it wasn't done specifically for that.
Comment: this is true only when login form is the only element in the page (or container). Otherwise, it varies. Being the only element in the page makes for it to be centered to draw the eye to it, but if you have other elements, it changes as needed
Comment: It's probably because the centered form has great completion rate and is consistent with mobile phones.
Answer: There are actually quite a few other benefits to this approach, I'll just rattle off a few.
Ergonomics.
An often overlooked part of UI design, because we think of digital as not being (as) limited by the human body. But what's more comfortable, looking straight forward, or looking to either the left or the right?
On phones, the middle of the screen is also considerably easier to reach than a side.

Focus
You want people to login, to look at your site. Centering the login creates as much buffer space as possible between the element you want used, and the world outside of the screen.

Consistency with other sites
Other sites do it, so you'll fit in nicely. While following the beaten path is not always the best option, in UX it can be good because it lowers the learning curve. This design is very archetypal, and people will instantly recognize the goal of the page and what to do next.

Consistency within variations
You can use the exact same layout for LTR and RTL text. You can load it on a phone or a PC and it will feel like the same layout. Equal whitespace fades into the periphery, but whitespace (or absence of it) on only one side makes a small or large site feel very different:
Answer: First of all

Why are login forms always centered on the screen?

They aren't. Some famous examples include Facebook, Stack Overflow, Office 365 (with the recent design change, they have centered their login form), Rediffmail, Yahoo (remember Yahoo!)
Symmetry
Symmetry is a phenomenon that is noticed throughout the universe. This makes the page look aesthetically pleasant, clean and keeps OCD at bay. Having anything center-aligned makes it easier to balance the layout which isn't very easy to do. Here's a good reference
Negative space
It's a concept that is used extensively by artists and photographers. Given that login forms generally are small, there's a lot of whitespace to deal with. Questions like how left is too left and how high is too to high get answered if the layout is center-aligned.
Responsive approach
Given that these sites would need to be made responsive at some point, squeezing and stretching from the center is comparatively easy.
Comment: @bfritz - Oh yeah! Just checked it out. Gotta say, I like the old one better :P
Comment: I just checked out the Office 365 login and a little grey box was floating above the form "We have a new sign-in experience! Try it now". I clicked it and it took me to a centered login form :)
Answer:
Obviously it's most aesthetically pleasing, but is there any other reasons why?

That's pretty much it.
Centered aligned login layouts have more pleasing visual white space surrounding them, which is certainly more visually pleasing.  Additionally, a small, center-aligned div means that the login form is generally easier to tweak for responsive design and mobile browsing.
Answer: There are many graphic design reasons why you'd want it centered, but it also draws attention. The screen center usually being the center of attention, being the assumption. Opening forms (dialogs) in the periphery of the user's field of view might mean they click the button and don't see an effect, so think the button doesn't work.
Also, if you are not logged in, you can't use the site.
If you look at some forums that can be used even when not logged in, many of them have a login form somewhere in the upper right, just two text fields, or as a popup from a "Log in" button.

Why are login forms centered?


Find $\lim_{n \rightarrow \infty} \int_0^n (1+ \frac{x}{n})^{n+1} \exp(-2x) \, dx$

Question: Find:
$$\lim_{n \rightarrow \infty} \int_0^n \left(1+ \frac{x}{n}\right)^{n+1} \exp(-2x) \, dx$$
The sequence $\left(1+ \frac{x}{n}\right)^{n+1} \exp{(-2x)}$ converges pointwise to $\exp{(-x)}$. So if we could apply Lebesgue's monotone convergence theorem, we have:
\begin{align}
\lim_{n \rightarrow \infty} \int_0^n \left(1+ \frac{x}{n}\right)^{n+1} \exp(-2x) \, dx &=\lim_{n \rightarrow \infty} \int_{\mathbb{R}} I_{(0,n)(x)} \left(1+ \frac{x}{n}\right)^{n+1} \exp(-2x) \, dx \\[10pt]
&= {} \int_{- \infty}^\infty \exp(-x) \, dx= +\infty
\end{align}
Can someone help me to prove that the sequence of integrands is monotone?
Answer: Using the indicator function, we can write
$$\int_0^n \left(1+\frac xn\right)^{n+1}e^{-2x}\,dx=\int_0^\infty \left(1+\frac xn\right)^{n+1}e^{-2x}\xi_{[0,n]}(x)\,dx$$
Then, note that for $0\le x\le n$, we have
$$\left(1+\frac xn\right)^{n+1}=\left(1+\frac xn\right)\left(1+\frac xn\right)^{n}\le 2e^{x}$$

EDIT:  The OP requested a source for the preceding inequality.
  In THIS ANSWER, I showed using only the limit definition of the exponential function along with Bernoulli's Inequality that the exponential function satisfies the inequality $$e^x\ge \left(1+\frac xn\right)^{n}$$for $x>-n$.

We can assert, therefore, that
$$\left(1+\frac xn\right)^{n+1}e^{-2x}\xi_{[0,n]}(x)\le 2e^{-x}$$
Applying the Dominated convergence theorem, we have
$$\begin{align}
\lim_{n\to \infty} \int_0^n \left(1+\frac xn\right)^{n+1}e^{-2x}\,dx&=\int_0^\infty \lim_{n\to \infty}\left(\left(1+\frac xn\right)^{n+1}\xi_{[0,n]}(x)\right)\,e^{-2x}\,dx\\\\
&=\int_0^\infty e^{x}\,(1)\,e^{-2x}\,dx\\\\
&=1
\end{align}$$
Comment: @scaremonger I added a highlighted section that gives a reference to an answer I posted in which I showed the inequality.  - Mark
Comment: Sorry, but could you yet explain what this inequality comes from?
Answer: Seems easier to use dominated convergence. Hint: $1+t\le e^t$, so $(1+x/n)^{n+1}\le\dots$; for $n\ge 2$ this is less than or equal to $\dots$.
Comment: @scaremonger Yes, limits preserve inequalities. That does not show what you said! What you said is like saying $\lim 1/n <=0$, so $1/n\le 0$. Yes, the thing is less than $e^{n+1)/n$. And if $n\ge 2$ then $(n+1)/n\le3/2$.
Comment: $(e^{x})^{\frac{n+1}{n}}$?
Comment: @scaremonger $\lim_{n\to \infty}\frac{n+1}{n}=1$.
Comment: I see, so, because the limit preserves inequalities, we obtain that $ (1+ \frac{x}{n})^{n+1} \le e^x$.
Answer: Firstly, you have a mistake in your last line:
\begin{align}\lim_{n \rightarrow \infty} \int_{\mathbb{R}} I_{(0,n)(x)} \left(1+ \frac{x}{n}\right)^{n+1} \exp(-2x) \, dx = \int_{0}^\infty \exp(-x) \, dx= 1 \end{align}
and not $+\infty$ as you have it (because you integrated from $-\infty$ and not from $0$). You could also change variable first $y=\frac{x}{n}$: $$\int_{0}^{n} (1+ \frac{x}{n})^{n+1} \exp{(-2x)} dx=\int_{0}^{1} (1+y)^{n+1} \exp{(-2ny)} n\,dy$$ and now everything happens in $[0,1]$.
Comment: Oh, thanks. I've forgotten about the indicator...


Were Pandaria, Broken Isles, Northrend, Kul'Tiras and Zandalar also affected by the Cataclysm?

Question: I was wondering if Pandaria, Broken Isles, Northrend, Kul'Tiras and Zandalar were also affected by the cataclysm.
When questing through these places, I did not notice one of the NPCs say something about strange things happening over the last years, the earth shaking or anything.
So my question would be:

Were these places affected by the cataclysm?
if not, why not?
Comment: I think I've heard NPCs talk about the cataclysm in Pandaria. No clue about the other regions though...
Answer: Zandalar: Yes, definitely

Zandalar has been severely crippled by the Cataclysm, causing King Rastakhan's palace to list to one side, the spine of the land to split in two, a fissure to open in the floor of the forum, and the region of the island called Nazmir as well as other areas of the island began sinking beneath the waves.
But though Zandalar was indeed damaged, it did not sink as Zul predicted. While Zul and the Golden Fleet left Zandalar, those that stayed behind endured and rebuilt.

Kul Tiras: Affected, but apparently not damaged

Kul Tiras, the island nation, will not be visible at the start of
Cataclysm – something about tectonic plates shifting it out to sea....

Broken Isles: unlikely
I have found no written evidence about anything Cataclysm related. The Broken Isles are a lot older than the Cataclysm, but there is no mention about any changes or destruction in their history.

Pandaria: Thrall found it (first?) because of the Cataclysm, but no apparent damage

It was shrouded by magic mists, leaving the continent protected from the outside.

and

"His essence raced headlong through the leagues and leagues of earth that unfurled around him. He moved through the sun-baked soil of Durotar and then to the muddy banks of the Swamp of Sorrows. All the lands, no matter how remote or distinct, were connected in a way that he had never comprehended.
Apart from the areas he knew, Thrall encountered other places and oddities in Azeroth of which he had been ignorant.
Somewhere in the Great Sea was a mysterious island shrouded in mists..."

Northrend (and Outland): No
From an interview:

Any plans for Outland and Northrend (zones created in the previous two
expansions)?
We have started to talk about what we need to do because there's
currently no congruity between the story that we are telling in
Cataclysm and the one in Outland. It feels a little weird to have the
whole "Deathwing is back and has destroyed the world" and then you
walk into Outland and you're like "Hey! There's this guy, Illidan". We
don't exactly know how we're going to tackle that yet, but we
definitely want to find a solution.


ValueError: Invalid reduction dimension 1 for input with 1 dimensions

Question: The tf.reduce_mean() function sums the elements of an array in such a way that the index referred to in the axis argument.
In the following code:
import tensorflow as tf

x = tf.Variable([1, 2, 3])
init = tf.global_variables_initializer()

sess = tf.Session()
sess.run(init)

So for the line
print(sess.run(tf.reduce_sum(x)))

The output is: 6
In order to generate the same output, I need to sum all the elements in a way to reduce the number of columns. So I need to set axis = 1 right?
print(sess.run(tf.reduce_sum(x, 1)))

But I get an error:

ValueError: Invalid reduction dimension 1 for input with 1 dimensions

But if I set axis = 0, I get 6. Why is this?
Answer: The error you get is ValueError: Invalid reduction dimension 1 for input with 1 dimensions. This pretty much means that if you can't reduce the dimension of a 1-dimensional tensor.
For an N x M tensor, setting axis = 0 will return an 1xM tensor, and setting axis = 1 will return a Nx1 tensor. Consider the following example from the tensorflow documentation:
# 'x' is [[1, 1, 1]
#         [1, 1, 1]]
tf.reduce_sum(x) ==> 6
tf.reduce_sum(x, 0) ==> [2, 2, 2]
tf.reduce_sum(x, 1) ==> [3, 3]

Comment: because it is a row vector? but when I change the axis argument to 0 (row)  I get 6. Why is this?
Comment: as lordingtar explains above, while setting axis=1, you say TF to reduce along 1-D, which obviously raises an error. It looks to me that your misunderstanding what is 'row' on the one hand, and what is 'column' on the other one.
Answer: "Note that one way to choose the last axis in a tensor is to use negative indexing (axis=-1)"
Comment: Hi there, welcome to Stack Overflow!  Could you elaborate, linking this answer more to the user's question?  It seems that in the question their tensor was a 1D array.  Your answer would help if it was a 2D or greater array.


Am I using the CSS ID selector appropriately?

Question: I think I may not be understanding "ID's" and Classes in CSS.  In the following example, I am just trying to customize the way the single image is displayed.  I tried to simply just create a custom id for that image, and then in the CSS add the appropriate tags.
The CSS I wrote is not applying to the image.
And on a side note, can I create a custom id in CSS by just doing <id> instead of
  ?
<!DOCTYPE html>

Bens's Blog

About Me

Best Poems

Worst Poems

Comment: Yes, you are using it correctly. If you want the CSS rule to be more specific you can change it to `p#mypicture` In this case you should be applying the CSS to the image itself, not the paragraph tag.
Comment: In your script, you are changing paragraph instead of img (I'm thinking that you want to apply style to immage itself).
Comment: The question does not describe *how* the image rendering should be affected, and the code posted does not include *any* setting that would apply to the `img` element.
Answer: You're applying your CSS to the paragraph
 tag. You want this to respect your current DOM:
#mypicture img {
  outline-color : red;
  border-radius : 40px;
}

Answer: A better rule set is this:
#mypicture > img {
    outline-color: red;
    border-radius: 40px;
}

mypicture is a paragraph and you want the styles to be applied to the image within the paragraph.
Answer: Try applying the ID directly to the image:

Answer: The default value for outline-style is none.  So, setting color alone isn't enough to get the outline to appear.  Try setting outline-style: solid;.  The will put a square outline around the paragraph.
Since you are also setting border-radius, it makes me wonder if your intent is to round the corners on the image.  If so, you should apply the styles to the image instead of the paragraph.  If you want the outline to be rounded as well, use border instead of outline.
Answer: I would simply (on line 13) leave out the paragraph blocks and put the id inside the picture declaration.