Double vs. BigDecimal?

Question: I have to calculate some floating point variables and my colleague suggest me to use BigDecimal instead of double since it will be more precise. But I want to know what it is and how to make most out of BigDecimal?
Comment: Check out this one; http://stackoverflow.com/questions/322749/retain-precision-with-doubles-in-java
Answer: A BigDecimal is an exact way of representing numbers. A Double has a certain precision. Working with doubles of various magnitudes (say d1=1000.0 and d2=0.001) could result in the 0.001 being dropped altogether when summing as the difference in magnitude is so large. With BigDecimal this would not happen.
The disadvantage of BigDecimal is that it's slower, and it's a bit more difficult to program algorithms that way (due to + - * and / not being overloaded).
If you are dealing with money, or precision is a must, use BigDecimal. Otherwise Doubles tend to be good enough.
I do recommend reading the javadoc of BigDecimal as they do explain things better than I do here :)
Comment: Saying that "BigDecimal is an exact way of representing numbers" is misleading. 1/3 and 1/7 can't be expressed exactly in a base 10 number system (BigDecimal) or in base 2 number system (float or double). 1/3 could be exactly expressed in base 3, base 6, base 9, base 12, etc. and 1/7 could be expressed exactly in base 7, base 14, base 21, etc. BigDecimal advantages are that it is arbitrary precision and that humans are used to the rounding errors you get in base 10.
Comment: @Truong Ha: When working with prices you want to use BigDecimal. And if you store them in the database you want something similar.
Comment: Good point about it being slower, helps me understand why the Netflix Ribbon load balancer code deals with doubles, and then has lines like this: `if (Math.abs(loadPerServer - maxLoadPerServer) < 0.000001d) {`
Comment: Yep, I'm calculating the price for stock so I believe BigDecimal is useful in this case.
Comment: @extraneon I think you mean to say "if **accuracy** is a must, use `BigDecimal`", a Double would have more "precision" (more digits).
Comment: `BigDecimal` exactly represents only numbers which can be written as finite decimal numbers, i.e. `x*10^y` where `x` and `y` are integers.
Comment: I used to work at Exegy (high speed trading hardware platform as a solution). Everything was integer based. Precise representation of money. For example, USD would be in terms of cents, as integers.
Answer: My English is not good so I'll just write a simple example here.
double a = 0.02;
double b = 0.03;
double c = b - a;
System.out.println(c);

BigDecimal _a = new BigDecimal("0.02");
BigDecimal _b = new BigDecimal("0.03");
BigDecimal _c = _b.subtract(_a);
System.out.println(_c);

Program output:
0.009999999999999998
0.01

Does anyone still want to use double? ;)
Comment: @eldjon Thats not true, Look at this example:

BigDecimal two = new BigDecimal("2");
BigDecimal eight = new BigDecimal("8");
System.out.println(two.divide(eight));
This prints out 0.25.
Comment: @EliuX Float may work with 0.03-0.02, but other values are still imprecise: `System.out.println(0.003f - 0.002f);` BigDecimal is exact: `System.out.println(new BigDecimal("0.003").subtract(new BigDecimal("0.002")));`
Comment: Nonetheless if you use a float instead you get the same precision than BigDecimal in that case but way better performance
Comment: But this is because you are not printing the float point properly. The idea is use double to do calculations. Once you get the result, transform it to BigDecimal. Set up your precision and rounding settings and print it.  Alternatively you can use a Formatter
Comment: For example 0.00999999999998  rounded gives you exactly 0.01
Comment: can someone explain why does this happen?
Answer: There are two main differences from double:

Arbitrary precision, similarly to BigInteger they can contain number of arbitrary precision and size (whereas a double has a fixed number of bits)
Base 10 instead of Base 2, a BigDecimal is n*10^-scale where n is an arbitrary large signed integer and scale can be thought of as the number of digits to move the decimal point left or right

It is still not true to say that BigDecimal can represent any number. But two reasons you should use BigDecimal for monetary calculations are:

It can represent all numbers that can be represented in decimal notion and that includes virtually all numbers in the monetary world (you never transfer 1/3 $ to someone).
The precision can be controlled to avoid accumulated errors. With a double, as the magnitude of the value increases, its precision decreases and this can introduce significant error into the result.
Comment: This answer truly explains the difference and the reason of using BigDecimal over double. Performance concerns are secondary.
Comment: @Meros - can you elaborate - "arbitrary precision" ?
Comment: https://docs.oracle.com/javase/7/docs/api/java/math/BigDecimal.html
Answer: If you write down a fractional value like 1 / 7 as decimal value you get
1/7 = 0.142857142857142857142857142857142857142857...

with an infinite repetition of the digits 142857.  Since you can only write a finite number of digits you will inevitably introduce a rounding (or truncation) error.
Numbers like 1/10 or 1/100 expressed as binary numbers with a fractional part also have an infinite number of digits after the decimal point:
1/10 = binary 0.0001100110011001100110011001100110...

Doubles store values as binary and therefore might introduce an error solely by converting a decimal number to a binary number, without even doing any arithmetic.
Decimal numbers, on the other hand, often store each decimal digit as is (binary coded, but each decimal on its own) or, in the case of BigDecimal, as two signed binary integer numbers in the form x*10y (thanks to @AlexSalauyou for pointing out). See: Class BigDecimal. This means that a decimal type is not more precise than a binary floating point or fixed point type in a general sense (i.e. it cannot store 1/7 without loss of precision), but it is more accurate for numbers that have a finite number of decimal digits as is often the case for money calculations.
Java's BigDecimal has the additional advantage that it can have an arbitrary (but finite) number of digits on both sides of the decimal point, limited only by the available memory.
Comment: _Decimal numbers (like BigDecimal), store each decimal digit as is (binary coded, but each decimal on its own)_---not true, `BigDecimal` stores number in form `x*10^y`, both `x` and `y` are stored as signed binary integers.
Answer: If you are dealing with calculation, there are laws on how you should calculate and what precision you should use. If you fail that you will be doing something illegal.
The only real reason is that the bit representation of decimal cases are not precise. As Basil simply put, an example is the best explanation. Just to complement his example, here's what happens:
static void theDoubleProblem1() {
    double d1 = 0.3;
    double d2 = 0.2;
    System.out.println("Double:\t 0,3 - 0,2 = " + (d1 - d2));

    float f1 = 0.3f;
    float f2 = 0.2f;
    System.out.println("Float:\t 0,3 - 0,2 = " + (f1 - f2));

    BigDecimal bd1 = new BigDecimal("0.3");
    BigDecimal bd2 = new BigDecimal("0.2");
    System.out.println("BigDec:\t 0,3 - 0,2 = " + (bd1.subtract(bd2)));
}

Output:
Double:  0,3 - 0,2 = 0.09999999999999998
Float:   0,3 - 0,2 = 0.10000001
BigDec:  0,3 - 0,2 = 0.1

Also we have that:
static void theDoubleProblem2() {
    double d1 = 10;
    double d2 = 3;
    System.out.println("Double:\t 10 / 3 = " + (d1 / d2));

    float f1 = 10f;
    float f2 = 3f;
    System.out.println("Float:\t 10 / 3 = " + (f1 / f2));

    // Exception!
    BigDecimal bd3 = new BigDecimal("10");
    BigDecimal bd4 = new BigDecimal("3");
    System.out.println("BigDec:\t 10 / 3 = " + (bd3.divide(bd4)));
}

Gives us the output:
Double:  10 / 3 = 3.3333333333333335
Float:   10 / 3 = 3.3333333
Exception in thread "main" java.lang.ArithmeticException: Non-terminating decimal expansion

But:
static void theDoubleProblem2() {
    BigDecimal bd3 = new BigDecimal("10");
    BigDecimal bd4 = new BigDecimal("3");
    System.out.println("BigDec:\t 10 / 3 = " + (bd3.divide(bd4, 4, BigDecimal.ROUND_HALF_UP)));
}

Has the output:
BigDec:  10 / 3 = 3.3333

Comment: damn, could you imagine the cops busting down your door at 2am... "Sir, is this your code? Are you aware that you used the wrong precision to divide these two numbers?! Up against the wall, NOW"
Comment: @Tarek7 This is indeed a legal problem for any calculation in banks, markets, telecommunications,... anything that is money related. If you've watched Superman, you understand that a simple change in precision can make you a millionaire!  :)
Answer: BigDecimal is Oracle's arbitrary-precision numerical library. BigDecimal is part of the Java language and is useful for a variety of applications ranging from the financial to the scientific (that's where sort of am).
There's nothing wrong with using doubles for certain calculations. Suppose, however, you wanted to calculate Math.Pi * Math.Pi / 6, that is, the value of the Riemann Zeta Function for a real argument of two (a project I'm currently working on). Floating-point division presents you with a painful problem of rounding error.
BigDecimal, on the other hand, includes many options for calculating expressions to arbitrary precision. The add, multiply, and divide methods as described in the Oracle documentation below "take the place" of +, *, and / in BigDecimal Java World:
http://docs.oracle.com/javase/7/docs/api/java/math/BigDecimal.html
The compareTo method is especially useful in while and for loops.
Be careful, however, in your use of constructors for BigDecimal. The string constructor is very useful in many cases. For instance, the code
BigDecimal onethird = new BigDecimal("0.33333333333");
utilizes a string representation of 1/3 to represent that infinitely-repeating number to a specified degree of accuracy. The round-off error is most likely somewhere so deep inside the JVM that the round-off errors won't disturb most of your practical calculations. I have, from personal experience, seen round-off creep up, however. The setScale method is important in these regards, as can be seen from the Oracle documentation.
Comment: BigDecimal is *part* of *Java's* arbitrary-precision numerical library. 'In-house' is rather meaningless in this context, especially as it was written by IBM.
Comment: @EJP: I looked into BigDecimal class and learned that only portion of it is written by IBM. Copyright comment below:

`/*
 * Portions Copyright IBM Corporation, 2001. All Rights Reserved.
 */`
Comment: _The round-off error is most likely somewhere so deep inside the JVM_---the error is hold not "deep in JVM", it is hold in assumption that 1/3 = 0.3333. When you make `new BigDecimal("0.3333")` the decimal 0.3333 is stored exactly.
Answer: If you need to use division in your arithmetic, you need to use double instead of BigDecimal. Division (divide(BigDecimal) method) in BigDecimal is pretty useless as BigDecimal can't handle repeating decimal rational numbers (division where divisors are  and will throw java.lang.ArithmeticException: Non-terminating decimal expansion; no exact representable decimal result.
Just try BigDecimal.ONE.divide(new BigDecimal("3"));
Double, on the other hand, will handle division fine (with the understood precision which is roughly 15 significant digits)
Comment: What about `divide(BigDecimal divisor, int scale, int roundingMode)`? This lets us specify exact precision of the division result which we will be happy with.
Answer: Your colleague just wants to make it simple.
Almost every value x written as decimal fractional number, cannot be exactly stored in binary-based double—thus, instead of x, there will be stored some x + delta. This is not a problem by itself, as in most cases transformation back to decimal handles it correctly (e.g.: Double.toString(0.1) -> "0.1"). But when you perform arithmetic calculations, deltas of arguments are accumulated in result, and you have to take care of it.
It is often said that is impossible to accumulate enough inaccuracy to affect result, as double has precision 1e-16 (i.e.: |delta| < 1e-16). This is true for x around 1. For x around 1M precision is 1e-10; for 100B (quite typical amount in Indonesian Rupiah), precision falls to 1e-5. Now you have a limitation of 100K simple arithmetic operations to guaranteerly stay in the safe zone.
Even if you are absolutely sure that accumulated inaccuracy won't spread into significant part of result, you have to implement some rules to suppress it: rounding, converting from cents, etc—every time when result should be treated as decimal, i.e. compared, printed, saved in database, sent to downstream, etc. And your colleague has to review all that.
With BigDecimal, where decimal fractions are stored accurately, given that all monetary amounts in modern world are counted in decimals, you and your colleague do not have this headache at all.

Double vs. BigDecimal?


Fastest way to acquire Cracked red eye orbs?

Question: What is the best/fastest way to acquire cracked red eye orbs?  I'm level 150 and short of dueling other Brotherhood of Blood members I cannot find a way to acquire these.  Dueling doesn't appear to be a very good method because it often takes over five minutes to land a duel.
Comment: Yes! Get more people sinning so I can punish them!
Answer: There are several monsters that drop the orbs:

Fire Salamanders in the cave under the Cardinal Tower bonfire.
Polearm wielding hunters in Huntsman's Copse.
The three Piglets to the right of the Majula Mansion.

The one that has given me the best drop rate is the Fire Salamander.
Here's a video of someone farming the little Piglets in Majula.
Also, Titchy Gren (The Brotherhood of Blood guy) sells them for 10,000 souls each in NG+
(As confirmed by @miR, burning an ascetic will not allow you to buy them).
Hope this helps a bit.
Comment: Actually,  I was disappointed to find that burning an ascetic did NOT work. Tried it shortly after reading this.
Comment: Can you burn an Acetic at the Titchy Gren Bonfire to get him to sell them in NG? I know it works with some NPCs and doesnt with others.
Comment: I have no reason to believe otherwise, every NPC has to act accordingly to the cicle in place.
Comment: That is disappointing, I'll make sure to add it to the answer.
Answer: Kill Elana(only once) in the first DLC and bonfire ascetic the first bonfire in the DLC, each ascetic nets you 5 cracked red eye orbs, 3 twinkling, 1 elizabeth mushroom. so basically you're getting almost 100k worth of items for 1 ascetic which you can buy for 7.5k and you dont need to buy any if you pick up all the ascetics throughout the game, youll have plenty to get 99 CREO and 99 twinkling titanite. If you run out of ascetics use the CREO in the chasm of old and get more 1 CREO for 1 Ascetic if you win.
Comment: The only problem is when you get to bonfire intensity 99 which means you can no longer get any CREO. but to think that you're getting 495 of them before you cant anymore, by this point youll cycle through 99 token of spites about 6/7 times so you would have about 200/300 hours on one character before it happens.
Answer: A bonfire at 99 intensity will still replenish items, just the number wont increase. Kill elana and the darklurker for ascetic farming. I got 85 CREO in about an hour and a half lats night


Set material density [kg/m³] instead of mass [kg]

Question: Is there any way or plugin which allows enter material density in [kg/m³] instead of direct enter real mass [kg] how it is now in Blender. Blender knows the exact size of the object, so it is possible to calculate volume [m³] and then evaluate weight [kg] based on material density. I personally don't understand why there is just weight [kg] by default. With material density, there could be also possible to preselect common material like wood, steel, iron, plastic, glass, etc. It will allow us to make more realistic physics animation in a much shorter time. Do it now with many objects on the scenes is horrible.
Comment: *Blender knows the exact size of the object.* - Does it? Where can we see the exact size? What if the meshes have a hole (or are non manifold), do they even have a volume then?
Comment: Yes. Of course, there is also several CAD extension which helps with precise modeling. And of course, that is possible to create a mesh that has no volume, but you will not use such an object for rigid body simulation. There is 3D Print extension directly in blender which can evaluate volume and are of any selected object, of course also with holes or with applied modifiers.
Answer: I found the solution, it is directly in blender itself.
Horizontal menu bar > Object > Rigid Body > Calculate Mass
As you can see here on the screenshot:

https://blender.stackexchange.com/a/137448/99511
Bad thing is that you need to do it every time you change the side of the object. It is not updated automatically.


adding a switch for direction reversal in 12v DC motor w/ PWM controller system

Question: I have a circuit for a 12v dc motor with a battery and a PWM controller. the system sort of is in this order battery-->PWM-->motor. I want to add in a switch to reverse the polarity to switch directions of the DC motor at will. Without the PWM, its a pretty simple operation and straightforward, but I was wondering how to do it now with the PWM. Do I put the switch after the pwm before the motor or between the battery and pwm? I wasn't sure how the PWM would affect the system direction and didnt want to ruin anything in my system while implementing the new switch
Comment: Welcome to EESE! If you put some additional effort in formulating your answer it is more likely to obtain a response. You have basically a single run-in sentence without any capitalization to break things apart, which hinders understanding. And a schematic, to illustrate what you are getting to, will save a lot of confusion and mental contortions. Please edit your answer, and you will find a simple schematic editor in the same edit box.
Answer: There are a few ways of doing this, but the easiest is the one to insert a DPDT relay in line with the motor.
Depending on the polary of the output, you might need to connect VCC instead of GND on the contact of the Relay, but the concept remains the same.
With a simple switch or a GPIO you can drive the relay and change the direction

simulate this circuit – Schematic created using CircuitLab
Answer:

Figure 1. Modifications required.
You can reverse the motor with a double-pole, double-throw (DPDT) switch.
Be careful with this. Reversing the motor while at speed will cause high currents to flow as the momentum of the motor must be overcome to reverse it.
Answer: Consider replacing the motor controller entirely with a H-bridge controller. A H-bridge is a motor controller that allows you to control speed with PWM and change direction with 2 digital IO pins.
The L298 is a popular one, plenty of modules available for cheap. You can control 2 DC motors with it.
Comment: the only reason I did not use the L298 is that I wanted a knob to control the speed at will, not use an arduino to program in the speed. and I really only need to control 1 dc motor
Comment: Do not use the L298 in a modern project. It is ancient and absolutely horrid.  If you use a bridge, use an FET one.  But the asker's requirement doesn't need electronic reversing.


Double light switch with one red and three black wires

Question: I'm in the middle of a diy kitchen remodel on an older home.  In the beginning of the remodel I had some cabinetry fall and break a double light switch.  One switch controlled a light above the sink.  The other switch controlled an outlet below the sink for the garbage disposal. The 2nd outlet was always on and used for the dishwasher.  I'm trying to install a new switch and think I got my wires mixed up.  There are three black wires and one red wire.  I attached them the same way they had been (or so I thought). Red wire on black screw top left, and the black wires on the other black screw and two brass screws.  Now one outlet works when one of the switches is turned on.  The other outlet has no power, and the other outlet doesn't send power to light.  Currently there is no light installed, just wires.  But I don't get any reading from my voltage detector.  From what I've read, the black and red wire that are paired together should be connected to the brass screws.  They both go to the outlet below the sink.  I tried connecting them like that, on the brass screws and was the same outcome.  The brass clip connecting the black wires has been broken.  I figured I'd try asking online before calling an electrician.
Thank you.
Comment: Can you provide a few pictures of the switch box and outlet box?
Answer: I figured it out.  Tried a new switch without breaking the brass tab connecting the black screws and it works perfectly.


Cosmic Microwave Background and heat flow

Question: Can the fact that energy is distributed homogeneously in the universe be explained through heat flow and not the Cosmic Microwave Background(or in other words, can we say CMB is a result of heat flow and not the universe expanding from a singularity)?
Comment: What do you mean by *heat flow*? Since the universe isn't a solid or liquid heat *heat flow* must be radiation, which is of course what the CMB is.
Comment: It is unclear what you are asking, as pointed out clearly in the comments above.
Answer: The evidence for the expansion of space does not come from the Cosmic Microwave Background. It comes from measuring the velocities of receding galaxies and clusters of galaxies, the velocity measured byt the  doppler effect found in spectra of specific atoms from distant galaxies.
The cosmic microwave background was a prediction of the expanding model of the universe and was found by observation later.
The homogeneity of the distribution is another story, and would be unexpected if the universe developed for 13+ billion years randomly, as in the beginning there was not thermodynamic possibility of uniformity in the energy spread in the  Big Bang model: due to relativity not all regions could exchange energy with all regions so as to attain thermodynamically uniform distributions. Within the BB model this forced the inflation period in the beginning and  postulating quantization of gravity and the inflaton making the distributions uniform.
Comment: Oh! Thanks guys. I guess I was too confused. Your answers helped clear some errors in my understanding. Thank you!


Show that the field of fractions of $\mathbb{Z}[[x]]$ is properly contained in $\Bbb Q((x))$

Question: I've been working on this for a while but I don't know how to proceed. Here it's what I've done:
Clearly, my goal is to show that every element of the field of fractions is in $\Bbb Q((x))$ and to show that there exist an element of $\Bbb Q((x))$ that is not an element of the field of fractions.
The problem suggests considering the series expansion for $e^x$ so that's what I did. I guess that that's the hint because $e^x$ is the element in $\mathbb{Q}((x))$ that is not in $\text{Frac}(\mathbb{Z}[[x]])$ I'm looking for. So
$$e^x=\displaystyle \sum_{n=0}^\infty \frac{x^n}{n!}$$
Since $n!\in\mathbb{N}$ then $\frac{1}{n!}\in \mathbb{Q}$ and $e^x\in \mathbb{Q}((x))$
Now, this is where I can't go further. I've tried assuming that $e^x\in \text{Frac}(\mathbb{Z}[[x]])$ and using that it must be a unit to achieve a contradiction but I don't know how to do so. Any hints? Thanks in advance
Answer: Write $e^x = A/B$ with $A,B \in {\mathbb Z}[[x]]$. We may assume that the constant terms of $A,B$ are not zero. Then write $B = b_0 + b_1 x + \cdots$.  Now take $R := {\mathbb Z}[ b_0^{-1} ]$ and $S := R[[x]]$. Then $B$ is a unit in $S$. So we can write $A/B = C$ for some $C \in S$. But we can't write $e^x$ as an element of $S$.
Answer: Suppose $e^x\cdot q(x)=r(x)$, with $q$ and $r$ in $\mathbb{Z}[[x]]$. If $p$ is a prime, then the coefficient of $x^p$ in $e^x\cdot q(x)$ is
$$ \sum_{i=0}^p \frac{q_i}{(p-i)!} $$
where $q_i$ is the coefficient of $x^i$ in $q(x)$. Since this has to equal $r_p$, we can mutiply both sides by $p!$ to get
$$ q_0 + p(\cdots)=p!r_p $$
so that $p$ divides $q_0$.  Since $p$ was an arbitrary prime, we see that all primes divide $q_0$, and so $q_0=0$.  We can then proceed inductively to show $q(x)=0$, and thus $r(x)=0$ as well.


Does a hard drive remember bad sectors after formatting?

Question: On an NTFS-formatted hard drive with some bad sectors, does the hard drive still remember bad sectors after Windows's diskpart clean is used to remove the NTFS volume?  What about clean all?
Comment: Depends on the hard drive. I remember drives with a hand-written table of bad sectors, on the  label, beneath the serial number!
Answer: NTFS remembers bad clusters. A cluster is considered bad if any sector in it is inaccessible. Since the cluster badness information is stored in a file ($BadClus, specifically), that information will get blown away if the NTFS volume is removed. (clean and clean all are essentially the same in that regard. clean all does a more thorough destruction of the disk's data, while clean just wipes the partition table.) Further reading: NTFS System (Metadata) Files.
The hard drive is what remembers bad sectors. Exactly how it does that depends on the model of the drive, but most modern disks automatically detect and remap dead sectors so that the operating system doesn't even know there's a problem. In that case, nothing the OS does can affect the disk's internal bookkeeping.
As others (notably harsh's answer) mentioned, if the OS can see bad sectors, the disk may have run out of internal spare sectors. (Especially true if the failure is returned on a write.) Bad ThingsTM will probably happen soon if you do not replace it.
Comment: The harddisk has spare sectors to use instead of those gone bad.  (This can be investigated with S.M.A.R.T).   If the drive starts reporting bad sectors back to the operating system, it means it has run out of spare sectors, and will likely soon go bad.  It is then advisable to replace the disk with a new one.
Comment: @ThorbjørnRavnAndersen No, that's not true. If a sector goes bad, and the OS tries to *read* it, the disk can do nothing but return an error—it can't replace it with a spare, because it has no way to know what data to put there. That'd lead to silent data corruption. If after *writing* to a sector it remains bad (the write itself fails, or reading it back does), then there is a problem.
Comment: @derobert Good info. I've adjusted my answer slightly. I'm sure the disk updates its own bad sectors table when a read fails, in addition to notifying the OS.
Answer: If the OS is encountering bad sectors, the drive's internal bad block table is probably full (as Ben N pointed out) and it is time to retire the drive.  Drives typically don't stop failing.
Comment: @RodSmith, not so much.  AFAIK, Windows happily flags the cluster bad after a read failure without trying to re-write the sector. This is usually why they "go away" when you format; because that causes a write and that fixes the problem.
Comment: If I could uptick this answer multiple times, I would. If the OS is showing bad sectors, it's time to retire the disk. Anything less is taking a huge risk with your data.
Answer: Out of the factory, the HDD is capable of re-mapping bad sectors to "spares" on inner cylinders. Your SMART diagnostics will record the count. This can be Googled easily enough. Needless to say there will be a seek delay even if your drive is "defragged". In the bad old days the HDD cam with the bad sectors named on a label affixed to the drive for listing in a low level format.
This remapping is abstracted from the OS, which will remember bad "clusters" and to answer your question, may have to re-learn bad clusters.


Why do people hate "chuggers" in DkS2?

Question: I have seen many times people who drink estus during PvP being called "chuggers", or being mocked or criticized. Why is that? Is it just because drinking estus tends to make the battle last longer?
Comment: @user1337 It's sort of based on that principle however. In DkS1, invaders couldn't use Estus, so in PvP, the host would not use their Estus in the fight to make it fair - the Gentleman's agreement. This has carried over to DkS2 - some people even drink *all* their Estus before the fight, to prove they will not be using it.
Comment: It makes the fight unfair. Of course people aren't going to like when other people don't follow their code of honor or whatever.
Comment: @user1337 Why unfair? Everyone has access to estus flasks... unless you are doing some sort of challenge or whatever.
Comment: Ah. I've only got experience with DS1, so I assumed invaders couldn't use estus based on that. But yeah, it's the same reason some people in LoL complain that their enemy got a "noob champion" and such excuses. At least that's what it feels like.
Answer: I've not had a great deal of experience with PvP, but from what I've seen it's so that a fight is as fair as possible.
Even if people are similar levels, one may have found more estus flask shards than their opponent, therefore if estus healing is allowed then one person has an immediate advantage, no matter their build, skill or play-style.
Having an unspoken agreement about using no estus means that duels can occur with minimal discrepancy between the players, and allowing a more balanced fight. It also means that skill is more relied upon, and mistakes are punished harder than just being able to rectify it with a quick chug.
This unspoken agreement also follows on from Dark Souls 1, where invaders (using the Red Sign Soapstone) were unable to use Estus. So, as a "Gentlemen's Agreement", both parties did not use their Estus during the fight.
However, I believe that if someone is invaded (e.g. via a red orb), all bets are off. This is no longer a mutual agreement to fight, as one player now has the advantage of surprising someone who may be attempting to simply play PvE.
There are of course people who will complain either way, and accuse people who have been invaded for not playing fair, despite never having agreed to be invaded. In addition people agreeing to a duel cannot be surprised if they did not establish this rule before the fight began. Most people may simply assume that everyone follows this rule, as many people accept it thus they feel that it doesn't need to be said.

Why do people hate "chuggers" in DkS2?


Question regarding the expected value of the momentum of a Gauß distribution

Question: Given the position amplitude
$$\psi(q) = \frac1{\sqrt{L \sqrt{\pi}}}
e^{-\frac1{2}\left(\frac{q-q_0}{L}\right)^2}
$$ I get the expected value for the position $$\langle \hat{q} \rangle = q_0$$ which makes sense to me but the expected value for momentum I get $$\langle \hat{p} \rangle = 0$$ which for me is kind of unintuitive. Is there a reasonable explanation of why this is the case? A Gauß distribution in my eyes should be one where the particle is the most localized (and the distribution with the lowest uncertainty) but shouldn't you still expect a non-zero momentum? To add to that, if u multiply a complex exponential function so u get
$$
\psi(q) = \frac1{\sqrt{L \sqrt{\pi}}}
e^{-\frac1{2}\left(\frac{q-q_0}{L}\right)^2} e^{i k_0 q}
$$ u also get a non-zero expected value for the momentum being $$\langle \hat{p} \rangle = \hbar k_0.$$ How can u interpret this physically?
Answer: $p$ can be positive or negative and when you average, they cancel.   $\sqrt{<\hat p^2>}$ will give the sort of answer you would expect.
Answer: Well of course you can take the Fourier transform of $\psi(q)$ to get $\psi(p)$, and you will find $\langle p\rangle=0$ but intuitively
$$
\psi(q)=\frac1{\sqrt{L \sqrt{\pi}}} e^{-\frac1{2}\left(\frac{q-q_0}{L}\right)^2}
$$
is solution to the time-independent Schrödinger equation (in a harmonic potential) so that $\langle x\rangle$ will be independent of $t$.  You can then think that
$\langle p\rangle = m\langle \dot{x}\rangle =m\frac{d}{dt}\langle x\rangle=0$.
The second case, where you have shifted your Gaussian (in $p$-space) is no longer a solution to the TISE but in fact a coherent state and it's expectation values for $\langle x\rangle$ and $\langle p\rangle$ are discussed in this post.
Comment: Thanks alot for the explanation that makes alot of sense


Can't Install Apps using Software Center

Question: I just installed Ubuntu 16.04. I was pretty exited about it but when I opened Software Center to download certain apps like GIMP, Python etc. but it showed no results found. I referred to many websites and they show that these apps are available on the Software Center. I have also tried using terminal but it still doesn't work. Please help me!!!
Comment: First of all you need to fully update you system before using the software center. Do so with *sudo apt update && sudo apt full-upgrade* in terminal. Then everything should work as expected.
Answer: I think Software centre is not indexed properly / not working properly these days. Don't quote me, I am not an expert. I have never really used it anyway. I use synaptic package manager for managing my software packages, why not give that a try and see how you get on.
 sudo apt-get install synaptic

It will appear in your main menu, run it then enter whatever you like in the search box. Select and install packages.
Comment: -1 Not an answer. Suggestions such as yours should go in the comments.
Comment: I have to disagree. I beleive I have provided an answer. A solution to the issue. Use Synaptic instead. However, I'm not particularly argumentitive. Suggestion, answer, idea, whatever. I am just trying to engage in the question.
Comment: Not being argumentative either but what's the point of installing additional software? The standard one just need updates that can and should be done in terminal or just opening the Updates utility. Besides Synaptic is a dangerous tool for newbies, I've seen too many people borking their system due to incorrect Synaptic use, deleting stuff they shouldn't...
Comment: The point of installing additional software is to have a tool to get the job done. After all, the sofware centre is indeed a tool for installing additional software. I've seen many people kill there system using the software centre, command line apt-get, command line apt, aptitude and synaptic.  I stand by my comment that synaptic (or in fact command line apt-get) is the best way to go.  I personally really don't like the software centre, and so that's my genuine advice. That said, feel free to remove my answer as the issue has been resolved anyway.
Answer: Quick answer workaround solution:
The default [ GNOME Software ] was just not working for me.
Literally 5 mins ago I installed the [ Ubuntu Software Centre ]

sudo apt-get install software-center

I am now back to what I am used to in previous Ubuntu versions.
All working fine now for me.

Here is a more detailed discussion:
Can I go with Ubuntu software Center if Ubuntu Software (on 16.04) isn't working properly?
Comment: -1 Not an answer. Suggestions such as yours should go in the comments.
Comment: Point taken. I offered a solution - and not an answer. Will be aware of the distinction in future.


Precision voltage reference for load cell and ADC

Question: I want to know what could I use to have a stable 5V excitation voltage for my load cell(wheatstone bridge) which I could also use to have a stable 5V reference voltage for my arduino adc. Would a LM7805(positive voltage regulator) could be applicable for this or I need to use a precision programmable reference like a TL431?
Answer: Virtually "any old voltage" will do if the "any old voltage" is used for both bridge excitation AND ADC reference voltage. Basically you will get no errors theoretically. This is called a ratiometric measurement.
Comment: Good one! +1 for you. :-)
Comment: so it would be more applicable if i use the same amount of voltage for both bridge excitation and ref voltage? because I have a 12V voltage source and i am planning to use it to my bridge and will regulate it to 5V for my adc
Comment: Use precisely the same voltage reference indeed - share the node between bridge and ADC reference - any filters you add, make them common to both bridge and reference. If you do this then you needn't worry about drift because it'll have no effect. I see you may have "accepted" the answer you understood rather than the best answer!!!


Why is TV remote's infrared wave shown by a camera as purple light, why not red or something else?

Question: I've always seen that all the old model remotes that is used in DVD players or TVs, it emits electromagnetic waves, having wavelength somewhere in the Infrared region. But when my phone's average quality camera (Moto E) is held between the emitter and my eyes, it converts the infrared into visible ones and shows a whitish purple colour. I don't know why always the purple is shown. I'll be very happy if you explain this to me.  Thank you.
Comment: I don't really think this has any meaning behind it. The camera detects the radiation emitted by the remote. This information get's processed into a signal which than is displayed. There obviously is not a 1:1 transfer from what is detected to what is displayed (since than you couldn't see the infrared signal from your remote anymore).
Comment: Interesting observation. I've noticed that infrared from tv remotes appear as purplish in color but never really thought about it. Apparently, both 'red' and 'blue' pixels are responding to the infrared. The 'red' and 'blue' pixel sensors are essentially the same, except that they are covered by red and blue filters, respectively. I would guess that whatever material is being used for the blue filters has high optical transmittance not just in the blue light range but also some transmittance in the near infrared.
Comment: @t.rathjen most run of the mill digital cameras use rgb photodiodes and then some interpolation. Isn't it strange, that the camera appears to behave, as if the blue diode is being excited? Unless of course the interpolation is cyclic, which would sort of make sense.
Comment: @LLlAMnYP, there's no such thing as an rgb photodiode.  Cameras use red, green, and blue filters to discriminate colors.  As Carl Witthoft's answer (below) explains, the color filters actually allow a small portion of IR to reach the sensor, and the light from a remote is sufficiently bright for that small portion to show up in the image.
Comment: @jameslarge I wish I could even remotely remember what I meant by "rgb photodiode". Probably three separate diodes, much like human photoreceptors.
Answer: The comments are on the right track.   First thing:  the R,G,B filters in a standard digital camera each pass some IR light, i.e. they're not low-frequency blocking. Usually cameras add an IR-blocking filter on top of the color grid because of this.    An example RGB filter from FujiFilm is shown in this picture:
   which is from somewhere near  here  You can see the Blue sensitivity in the Near-IR.
EDIT:  Just to clarify: the three curves are for different thicknesses of the color filters, not (0.7, 0.9, 1.1 $\mu m$) wavelengths
Camera manufacturers are usually unwilling to release their color filter specifications, unfortunately.  You might get lucky if you Google around for your particular model.


Do you have any experience with Pokémon GO and slow internet?

Question: does someone has experience with playing Pokémon GO when you have used all FUP, so your connection was slowed?
I am talking about 32kbps for downloading and 16kbps for uploading.
Answer: All games by Niantic (Pokemon GO and Ingress) are capable of supporting very low bandwidth connections without a problem. Ingress players have been known to play through BGAN terminals, which can be slower than Dial-Up at times.
Mapping data and Pokestop Image data will take a rather decent time to load, but they will be available for the rest of your game session. As long as you do not close the game or move into a new region, you will still be able to play. Note, however, that Pokemon spawns may take a very long time, and catch confirmations may take just as long.
Combined with current server instability, Pokemon GO on such a slow connection will definitely be possible, but may very well be an exercise in futility.
Answer: Yes, you will have a hard time downloading maps and images.
You will have to download Google Maps for your region as offline maps in order to have a chance to play. Circling your home area won't cause much traffic, but going further away might have an impact on your game as it keeps loading data (images from PokéStops, arenas, etc).
Edit: As mentioned below there is a chance the offline maps no longer work, but I haven't found a reliable source, yet. This would require kinda large downloads, if you leave your home area.
Comment: I may have heard wrong but the offline map download has been debunked
Comment: I've heard about that, but I don't think they fixed it, yet. Seeing my traffic from yesterday and today it's not abnormally high like it used to be before I downloaded the maps.
Comment: The map download didn't do much for me IMO. But maybe I need to do it just for a bit longer and I might see the difference.
Comment: I guess that depends on how far you travel. For me that's 200 km every day and downloading all those maps have a good impact on your traffic. Especially with 32kb download it's a pain to download several 20-30 MB map packs. Let me know, if you see a difference after going further.
Comment: Ah that is indeed alot... I will come back to this when I have extra info!


Which one are the best TIPS to make a logo for web?

Question: i need to make a logo for a development company,and the logo will be displayed in screen most of the time, so i will like to know every tips to make the logo more responsive and totally functional. If you have a video or any source where to find advice it will be pretty nice.
Answer: Even though your logo will appear onscreen most of time, I would still recommend designing it in vector format with Adobe Illustrator. YOU NEVER KNOW WHEN THEY'LL NEED IT FOR PRINT. Then, you can create a variety of sizes in bitmap form for your client so they can choose the appropriate size.  Including pngs too so they can use it over a color background. If you just give them one file as a jpeg, they could unwittingly use it at a much larger size and you'll be disappointed with the degradation that occurs. Hope this helps,
Ellen


Old light was working and now the new one isn't

Question: I just installed a new light fixture in my kitchen where an old one was. I have it all wired-up the same as the old light, but it doesn't work. Would a picture(s) of my wiring help you to see what I did wrong?
Comment: Hello, and welcome to Home Improvement. We'll need a **lot** more information before we could help you (e.g. pictures, wiring diagram, etc).
Comment: Did you hook the new light to the exact same wires the old light was hooked to?  Or did you take them all apart?  Were any white wires wire-nutted to black wires?
Answer: Okay ... if it doesn't work they you have to start over (obvious answer) but before you rip everything out you might want to check the bulb (it seems crazy but I've seen and even done some very forget things myself like turning on a new light with no bulb and doing the classic facepalm ... not saying you did that, just that I have before myself).  If it's not a simple bulb, then did you flip a circuit breaker and before working on it and not reset the breaker?
After those two somewhat obvious tests, remove the light and see if the light is a functional light (I would rig up my own test involving alligator clamps attached to the end of a cut off old electrical cord I've made myself for testing electrical things and then plug it into an outlet (if you're not comfortable with electricity basics, like not getting yourself shocked, then please don't try what I described above ... I've been shocked a few times and over the years have a very healthy respect for the power of electricity).
After taking everything apart, test to make sure that the switch you think controls those wires actually does (yeah, I read "the old light was working part" but if the switch doesn't control the wires then you might have replaced the wrong thing ... switches go bad too and last summer I replaced a light switch that was shocking my sister in her house even after the switch tested out fine.  The shock was my clue that something wasn't fine so after not finding any other problem I merely replaced the switch.
That's all I can guess for you for now with the limited information you provided.  If you have access to a volt meter or other electrical testing device then your troubleshooting will be much quicker but that's kind of pricey if it's not a tool you will use very often.

Old light was working and now the new one isn’t


What Size Screws Should I Use to Mount an Electrical Box Bar Hanger?

Question: What size/type screws should I use to mount a Raco electrical box bar hanger (Model #920) to studs?
Comment: you know how grounding screws must be 10-32?  This is nothing like that.  This is meant to be "bapped in" by framing guys with whatever they got in their pouch or mag. I would pre-drill and use screws, but only because of my lack of experience not cracking wood.
Comment: Not being picky here, but I presume this is to mount something to a ceiling. The horizontal framing members above the finished ceiling are called joists, not studs. Studs are the vertical framing for the walls.
Answer: The screw should not be larger than the factory drilled hole which looks to be 1/4".  Typically seen in the field are #10 x 1" Slotted Hex Washer Head Sheet Metal Screw.
You can go longer than 1" but for that bar hanger probably not necessary.
Comment: +1 The pressure on the screws is virtually all shear (perpendicular to the length of the screw) so length is almost immaterial. Just long enough to grab solidly. There is no tension (pull out) force.
Comment: The bar hanger pictured is a type used in new construction. It can be used in finished construction where one can go into the attic and get at the ceiling joists, but it really cannot be installed *from the living space through an existing hole*. If you have a ceiling light fixture in place already and want to install a ceiling fan or a heavy chandelier, then there are other types of bar mount which can be installed from the living space without having to go into the attic. These other types don't even use screws. The bar expands and the ends penetrate into the sides of the ceiling joists.
Comment: One could use any variety of screw or nail, as long as the shank will go through the hole and the head will not, and it has enough depth to not pull out from shear load.  So that screw is far more specific than needed, but if you are working in close quarters you will want a drive method like Robertson, Torx, or hex as you picked, which won't cam out.


Rook Game Problem Solving

Question: Given a $9 \times 25$ chessboard, a rook is placed at the lower left corner. Players A and B take turns moving the rook. A plays first and each turn consists of moving the rook horizontally to the right or vertically above. The last person to make a move wins the game. At the completion of the game, the rook will be at the top right corner. For example, the figure below shows a $3 \times 4$ chessboard and the sequence of moves that leads to a win for player A. Does player A have a winning strategy in the given $9 \times 25$ chessboard? If so, what is the strategy? If not, what is player B's winning strategy?
Answer: This is Nim in disguise.  You have piles of $8$ and $24$.  $A$ can win by symmetry.
Comment: How it's possible explain me in detail
Comment: Did you look up Nim?  You have piles of stones and can take as many stones from one pile as you like.  The horizontal and vertical distances are your two piles.  You start 8 squares down and 24 squares left
Answer: In an $n \times m$ game  $(n\gt m)$ (the rook begins at $(0,0)$), $A$ has a winning strategy:
On your first move, you go to $(n-m,0)$. The winning strategy is then to end on the diagonal at the end of your turn.
If you play a  $n \times n$ game, $B$ has the exact same winning strategy.
In general, the first one the come on a $(n-k,m-k)$ tile wins.

Rook Game Problem Solving


EF6 Problems Connecting for Update-Database Command

Question: I am making changes to my database requiring EF migrations for the first time in years. This means that there have been lots of code base changes over the past 2 years, but this is the first time my model has changed for ages. I am using EF 6.1.3, VS 2017 and SQL Express installed on a server on the LAN.
I have EF migrations enabled on the project and am able to "Add-Migration". When it comes to "Update-Database", however, I have the following error:

A network-related or instance-specific error occurred while establishing a connection to SQL Server. The server was not found or was not accessible. Verify that the instance name is correct and that SQL Server is configured to allow remote connections. (provider: SQL Network Interfaces, error: 26 - Error Locating Server/Instance Specified)

I am aware that this sort of thing can happen when TCP connections have not been enabled, but I've double checked this and am able to connect to the database with no problems using the same DbContext object and connection string from my application. I can also use SQL Server Object Explorer. It's only Update-Database that fails. I'm on a domain and am using domain-level authentication.
Is there some other permission I need to enable to allow EF Migrations to work?
EDIT: For those who have suggested things like checking the startup project in the comments below, I am providing the start of the error trace. I have not provided the entire trace as that takes us through the whole Migrations Stack of function names. The relevant part including my exact command line is:
PM> Update-Database -ProjectName "AJSoft.CN2.Data.Model" -Verbose
Using StartUp project 'AJSoft.CN2.Data.Model'.
Specify the '-Verbose' flag to view the SQL statements being applied to the target database.
Target database is: 'CN2 Test' (DataSource: SERVER\SQLEXPRESS, Provider: System.Data.SqlClient, Origin: UserCode).
System.Data.SqlClient.SqlException (0x80131904): A network-related or instance-specific error occurred while establishing a connection to SQL Server. The server was not found or was not accessible. Verify that the instance name is correct and that SQL Server is configured to allow remote connections. (provider: SQL Network Interfaces, error: 26 - Error Locating Server/Instance Specified)

at System.Data.SqlClient.SqlInternalConnectionTds..ctor(DbConnectionPoolIdentity identity, SqlConnectionString connectionOptions, SqlCredential credential, Object providerInfo, String newPassword, SecureString newSecurePassword, Boolean redirectedUserInstance, SqlConnectionString userConnectionOptions, SessionData reconnectSessionData, DbConnectionPool pool, String accessToken, Boolean applyTransientFaultHandling)

The startup project is the project with access to the connection string and my result is the same whether I specify the "Model" project above or my actual WPF startup project.
Comment: Can you connect to the server via Sql Server Management Studio?
Comment: Are you including the \sqlexpress suffix in the conn string?
Comment: Yes - no problems there either from my dev PC or from the local PC.
Comment: Yes - I've double checked and the connection string is exactly the same whether my code or EF Migrations is accessing the database.
Comment: FYI, I also get the message "Target database is: 'CN2 Test' (DataSource: SERVER\SQLEXPRESS, Provider: System.Data.SqlClient, Origin: UserCode)." Which appears to be correctly implied from my DbContext.
Comment: First check your startup project and make sure the connection string is in there. Run `update-database -Verbose` for more info. You can also explicitly supply the project with the connectstring using the `update-database -StartUpProjectName MyProjectWithConnectionString` parameter.
Answer: OK - for anyone else looking at this, I have solved the issue.
On further thinking about this, there had to be a different connection string used for my project and for EF migrations, otherwise the message makes no sense.
The connection string provided to EF Migrations is set up in a static constructor to my custom DbContext class. As far as I was concerned, this was correct behaviour. However when the project is compiled and run, a settings file is read and my code adds some other information to the connection string.
That is why there was a discrepancy between the two - adding the information to the CS in the static constructor fixed the error.
Answer: My problem was that I had different environment (ASPNETCORE_ENVIRONMENT) set up for Package Manager Console than for my .NET Core project.
Use Get-ChildItem Env: in Package Manager Console to list your environment variables.
I used Update-Database -Verbose to see which environment is used by the command.
Than I changed my environment variable, restarted Visual studio and it used the correct project settings.


ASPX That Returns An Image - Output Cache-able?

Question: Greetings!
I've created an APSX web form that returns a remote image based on some supplied parameters.  It can be used like this:

ImageGetter.aspx's markup and code look similar to this:
<%@ OutputCache Duration="100000" VaryByParam="*" Location="ServerAndClient" %>
<%@ Page Language="C#" AutoEventWireup="false" EnableSessionState="False" CodeBehind="ImageGetter.aspx.cs" Inherits="ACME.Helpers.ImageGetter" %>

This code is called in ImageGetter.aspx's Page_Load method:
byte[] data = null;
Dictionary<string, string> file_locations = GetImageLocations(param1, param2);
try
{
    data = new WebClient().DownloadData(file_locations["main"]);
}
catch (WebException wex)
{
    try
    {
        data = new WebClient().DownloadData(file_locations["backup"]);
    }
    catch (Exception e)
    {
        throw;
    }
}
Response.ContentType = "image/jpeg";
Response.OutputStream.Write(data, 0, data.Length);
Response.End();

From my testing, it doesn't appear to be caching.  Is this possible to do with Output Caching or should I resort to writing my own cache to store the byte arrays depending on query string paramters?
Answer: Try dropping the Response.End() as this will terminate the thread prematurely and prevent output caching from taking place.
See: http://bytes.com/groups/net-asp/323363-cache-varybyparam-doesnt-work
You may wish to consider using an ASHX handler and using your own caching method.
Comment: ...because its now jumping through cache hoops?
Comment: Dropping Response.End somehow slows it down even more so.
Answer: Use an ASHX generic handler and use the HttpRuntimeCache (Cache object) to do the job as Codebrain said. It will be faster and WAY more flexible.
Answer: Your problem could be a bug in IE - it can't cache if the Vary:* HTTP response header is used, but IIS returns it by default because it's in the HTTP 1.1 spec.
Try adding the following to your web.config:
<system.web>
    <caching>
        <outputCache omitVaryStar="true" />
    </caching>
</system.web>


Scheduled run of stored procedure on SQL server

Question: Is it possible to set up somehow Microsoft SQL Server to run a stored procedure on regular basis?
Answer: Yes, in MS SQL Server, you can create scheduled jobs. In SQL Management Studio, navigate to the server, then expand the SQL Server Agent item, and finally the Jobs folder to view, edit, add scheduled jobs.
Comment: So strange to me that this answer has gotten more upvotes in the last year than in the time between 2008 - 2013. Why is that?
Comment: Well, I ended up here today due to a project requirement - and voila! another upvote for you!
Answer: If MS SQL Server Express Edition is being used then SQL Server Agent is not available.  I found the following worked for all editions:
USE Master
GO

IF  EXISTS( SELECT *
            FROM sys.objects
            WHERE object_id = OBJECT_ID(N'[dbo].[MyBackgroundTask]')
            AND type in (N'P', N'PC'))
    DROP PROCEDURE [dbo].[MyBackgroundTask]
GO

CREATE PROCEDURE MyBackgroundTask
AS
BEGIN
    -- SET NOCOUNT ON added to prevent extra result sets from
    -- interfering with SELECT statements.
    SET NOCOUNT ON;

    -- The interval between cleanup attempts
    declare @timeToRun nvarchar(50)
    set @timeToRun = '03:33:33'

    while 1 = 1
    begin
        waitfor time @timeToRun
        begin
            execute [MyDatabaseName].[dbo].[MyDatabaseStoredProcedure];
        end
    end
END
GO

-- Run the procedure when the master database starts.
sp_procoption    @ProcName = 'MyBackgroundTask',
                @OptionName = 'startup',
                @OptionValue = 'on'
GO

Some notes:

It is worth writing an audit entry somewhere so that you can see that the query actually ran.
The server needs rebooting once to ensure that the script runs the first time.
A related question is: How to run a stored procedure every day in SQL Server Express Edition?
Comment: is this a never ending process, an infinite loop ? is this will execute everyday at '03:33:33' ?
Comment: Use the following for a task that is run on a repeated interval (ideally add a check to prevent overlap such as via a monitoring table bit column [IsRunning]):  waitfor delay '00:05'
Answer: Yes, if you use the SQL Server Agent.
Open your Enterprise Manager, and go to the Management folder under the SQL Server instance you are interested in. There you will see the SQL Server Agent, and underneath that you will see a Jobs section.
Here you can create a new job and you will see a list of steps you will need to create. When you create a new step, you can specify the step to actually run a stored procedure (type TSQL Script). Choose the database, and then for the command section put in something like:
exec MyStoredProcedure
That's the overview, post back here if you need any further advice.
[I actually thought I might get in first on this one, boy was I wrong :)]
Answer: Probably not the answer you are looking for, but I find it more useful to simply use Windows Server Task Scheduler
You can use directly the command sqlcmd.exe -S "." -d YourDataBase -Q "exec SP_YourJob"
Or even create a .bat file. So you can even 2x click on the task on demand.
This has also been approached in this HERE
Answer: I'll add one thing:  where I'm at we used to have a bunch of batch jobs that ran every night.  However, we're moving away from that to using a client application scheduled in windows scheduled tasks that kicks off each job.  There are (at least) three reasons for this:

We have some console programs that need to run every night as well.  This way all scheduled tasks can be in one place.  Of course, this creates a single point of failure, but if the console jobs don't run we're gonna lose a day's work the next day anyway.
The program that kicks off the jobs captures print messages and errors from the server and writes them to a common application log for all our batch processes.  It makes logging from withing the sql jobs much simpler.
If we ever need to upgrade the server (and we are hoping to do this soon) we don't need to worry about moving the jobs over.  Just re-point the application once.

It's a real short VB.Net app: I can post code if any one is interested.
Comment: No, I don't need the code, only general idea. Many thanks. :)
Answer: You could use SQL Server Service Broker to create custom made mechanism.
Idea (simplified):

Write a stored procedure/trigger that begins a conversation (BEGIN DIALOG) as loopback (FROM my_service TO my_service) - get conversation handler
DECLARE @dialog UNIQUEIDENTIFIER;

BEGIN DIALOG CONVERSATION @dialog
        FROM SERVICE   [name]
        TO SERVICE      'name'
        ...;

Start the conversation timer
DECLARE @time INT;
BEGIN CONVERSATION TIMER (@dialog)  TIMEOUT = @time;

After specified  number of seconds a message will be sent to a service. It will be enqueued with associated queue.
CREATE QUEUE queue_name WITH STATUS = ON, RETENTION = OFF
             , ACTIVATION (STATUS = ON, PROCEDURE_NAME = <procedure_name>
             , MAX_QUEUE_READERS = 20, EXECUTE AS N'dbo')
              , POISON_MESSAGE_HANDLING (STATUS = ON)

Procedure will execute specific code and reanable timer to fire again.

You can find fully-baked solution(T-SQL) written by Michał Gołoś called Task Scheduler
Key points from blog:
Pros:

Supported on each version (from Express to Enterprise). SQL Server Agent Job is not available for SQL Server Express
Scoped to database level. You could easiliy move database with associated tasks (especially when you have to move around 100 jobs from one enviromnent to another)
Lower privileges needed to see/manipulate tasks(database level)

Proposed distinction:
SQL Server Agent (maintenance):

backups
index/statistics rebuilds
replication

Task Scheduler (business processes):

removing old data
preaggregations/cyclic recalculations
denormalization

How to set it up:

get source code from section: "Do pobrania" - To download
(enabling broker/setting up schema tsks/configuration table + triggers + stored procedure)/setting up broker things)
set up configuration table [tsks].[tsksx_task_scheduler] to add new tasks (columns names are self-descriptive, sample task included)

Warning: Blog is written in Polish but associated source code is in English and it is easy to follow.
Warning 2: Before you use it, please make sure you have tested it on non-production environment.
Answer: Using Management Studio - you may create a Job (unter SQL Server Agent)
One Job may include several Steps
from  T-SQL scripts up to SSIS Packages
Jeb was faster ;)
Answer: You should look at a job scheduled using the SQL Server Agent.


No settings appearing in the Properties Editor

Question: I have the object selected in Object Mode but the Properties Editor is not showing me any settings/options in order to allow me to add textures, modifiers, materials, etc. It's as if nothing is selected yet the object is selected. Switching back and forth between Object and Edit mode makes no difference. Cycles Render is selected. I'm running version 2.79b. I'm thinking its got to be something simple that I'm just overlooking but for the life of me I can't figure out what the problem is.
Comment: Possible duplicate of [Material setings in properties window is missing](https://blender.stackexchange.com/questions/27671/material-setings-in-properties-window-is-missing)
Comment: put your mouse pointer over the panel, then scroll up!
Comment: Thanks for the suggestion but that didn't work.
Answer: I fixed the problem. In fact I had somehow changed the menu to horizontal.
Right-clicking on the Properties panel and changing it from Horizontal to Vertical fixed this problem.
Comment: Nice! It actually looks like you encountered a bug that can be easily reproduced: in fact, even in "Horizontal", the first line should be visible anyway, but it isn't in some circumstances! I'll probably report it


Upgrade TFS 2015 to TFS 2018

Question: Since TFS 2018 does not support SharePoint integration, which databases should be migrated and what should be done with the SharePoint databases.
Answer: Update:
If you are upgrading to TFS 2018 from a previous version configured to integrate with SharePoint 2010 or 2013, you will need to disable the SharePoint integration after upgrade, or your TFS SharePoint sites will fail to load.
During installation, if SharePoint and TFS are on the same server, the installer will display the following warning message:

TFS 2018 and later versions no longer support integration with
  SharePoint. If you have configured TFS integration with SharePoint,
  then you will need to disconnect to the TFS Integration on each
  SharePoint server, or your TFS SharePoint sites will not work.

After upgrading the TFS server, you must uninstall the prior version of the TFS from the SharePoint server. After uninstalling the TFS, the TFS SharePoint sites will fail to load. This is because they reference TFS artifacts that no longer exist.
The solution is to install the TFS Disconnector for SharePoint on the SharePoint 2013 server. The TFS Disconnector for SharePoint installs all the required references for TFS sites to display properly, while disabling TFS-SharePoint integration.
After the upgrade, your TFS SharePoint sites will display, but all integration functionality is disabled. The following image shows what the site will look like after you upgrade and disable SharePoint integration.

For more information, read Disable SharePoint integration after TFS 2018 upgrade.
Also take a look at Future plans for TFS and VSTS SharePoint integration

There are a number of changes coming to Team Foundation Server requirements in TFS 2018. Details on requirements across versions of TFS can be found in requirements and compatibility. Before you upgrade to TFS 2018, take a look at below note:

Operating systems
TFS 2018 will not support Windows Server 2008 R2, Windows 7, Windows
  8.1, or Windows 10 Home edition. We have never recommended installing TFS on client OSes except for evaluation purposes or personal use. We
  will continue to support Windows 10 Professional and Enterprise
  editions.
SQL Server
TFS 2018 will no longer support SQL 2014, but will continue to support SQL 2016 and will add support for SQL 2017. We typically
  strive to support at least one "overlapping" version of SQL between
  major releases of TFS in order to make it easier to upgrade TFS
  deployments incrementally.
SharePoint
TFS 2018 discontinues support for the TFS Extension for SharePoint.
  For more information, go here:
  https://go.microsoft.com/fwlink/?linkid=852977.
Build compatibility
TFS 2018 will no longer support the XAML build system. For more
  information, go here:
  https://blogs.msdn.microsoft.com/bharry/2017/05/30/evolving-tfsteam-services-build-automation-capabilities/.

If your TFS2015 installed on a not support system, you may have to first set up a new operating system.
Even though there is not a complete tutorial for TFS 2015 to TFS 2018 upgrade procedure by now. You could refer this article aims to expand on the Upgrade overview and give a step by step walk-through of the upgrade to TFS 2017. You just need to take care of some notes mentioned above.
The general process for upgrading an existing deployment of Team Foundation Server is to:

Prepare your environment. Such as upgrade your SQL sever
(required), operating system...
Expect the best, prepare for the worst. The single most important step you can take here is to ensure you have a complete and consistent set of database backups.
Do the upgrade!
Configure new features.
Comment: Thanks for the reply, i have edited my question as it was put on hold. I understood the changes brought in to TFS 2018, my concern originally is to, what to do with the SharePoint data. Whether to decouple the SharePoint databases from that of TFS database and configure a new SharePoint all together, or we can have the SharePoint documents in somewhere in TFS itself.
Comment: @Angshuman  If you are upgrading to TFS 2018 from a previous version configured to integrate with SharePoint 2010 or 2013, you will need to **disable the SharePoint integration after upgrade**, or your TFS SharePoint sites will fail to load. For more information, read [Disable SharePoint integration after TFS 2018 upgrade.](https://learn.microsoft.com/en-us/vsts/report/sharepoint-dashboards/deprecation/disable-tfs-sharepoint-integration-after-tfs-2018-upgrade) You could still keep the share Point data. Details please see my update reply.
Comment: this is what i was looking for, marked this as answered. I am going to upgrade TFS into a new set of hardware so I guess I need to decouple the SharePoint then copy the databases.
Answer: I don't think that you will find one complete guide in doing this, but a source of information is the Requirements and compatibility page.
There are different considerations depending on your configuration, e.g. do you use SharePoint, Reporting Services etc. One thing that you need to deal with, is that TFS 2015 and TFS 2018 does not support the same versions of SQL server, so you will need to upgrade SQL during the upgrade or move your collection(s) to a new server with the appropriate version of SQL (see here).
I would suggest to do a test migration of one or more collections and sort out the process before attempting it on your production server.

Upgrade TFS 2015 to TFS 2018


I keep feeling my tyre has punctured

Question: Often while riding my scooter I get a feel that my rear tyre has gone flat as I experience sudden loss of pick up and can sense the engine is working hard and poor handling(all sort of signs of a flat tyre) but when i stop and have a look it's all ok.
I got a flat tyre recently and had to replace the tube ,I got it inspected by the mechanic he said the wheel and tyre condition is all ok but still I keep feeling the same sometimes.
NOTE: I always maintain the recommended tyre pressure.
Comment: one can imagine issues with wheel bearings or spokes (if spoke wheels) might feel like a flat tire.
Comment: I'm not discarding that there might be something wrong, but in my experience, after a recent flat tire I'd become a little paranoid about my tire. I'd be looking at it once in a while, only to realize it was all alright. It could be the case, but even if it is, I wouldn't turn that into an excuse not to check if everything is in order..
Comment: Has the surface you are riding on changed? tarmac to mud?
Comment: @SolarMike i mostly ride it in the city and the roads keep changing from cemented to tar made
Answer: Normally if the engine seems to be working or revving too high without driving the vehicle forward its an indication that there could be an issue with the clutch. If you're not sure this will need to be determined by your mechanic who should be able to inform you far better of the cause of the issue. If the bike has a manual gearbox perhaps something like a clutch cable adjustment is necessary, however if its an automatic different checks will need to be made.
Comment: its not like that my vehicle does not move forward but I experience poor acceleration and that too just for a while
Comment: The bike may well still pull away ok but It still sounds like the clutch is slipping whilst under load, this will result in poor acceleration as the amount of drive available to the rear wheel is reduced due to the slipping clutch.

I keep feeling my tyre has punctured


Given median survival and CI, and assuming an exponential distribution, can one predict survival and CI at a time point?

Question: I have access to a manuscript where the median survival and CI are reported. The shape of the curve approximately takes the shape expected for an exponential distributed failure time. I don't know the exact censoring distribution. Is there a useful approximation to convert the median survival (and CI) to the expected survival (and CI) at, say, 6 months? What assumptions about the censoring distribution need to be made for the approximation to work?
Comment: If you feel comfortable assuming it's really exponential, & that the censoring is independent / uninformative, then I don't see any problems.  You'd want to take the uncertainty in the CI into account.  Then I suppose you'd integrate over the results.  I think that's what I would do.
Comment: @gung-ReinstateMonica kind of internal strategy, trying to decide if some scant preclinical data on our end can compete with big game-changer studies.
Comment: What is it you want the expected survival at 6 months for?  Eg, is this for a power analysis?
Answer: Brookmeyer and Crowley (1982) provides general case solutions and exponential distribution solutions for median survival and calculation of confidence intervals.
Suppose $T$ is the distribution of event times, with $C$ the indicator of censor versus failure. The Kaplan Meier estimate $\hat{S}(t)$ of the overall survival is a consistent estimate of $1-F_{(t)}$ where $F$ is the cumulative distribution function for the failure process. Supposing $F(t)=1-\exp (-\lambda t)$, the median survival $F^{-1}(0.5) = M$ is given by $$M = \log 2 \sum (\text{observed survival times})/d$$ where $d$ is the sum of observed deaths. In fact, $\sum (\text{observed survival times})/d$ is the MLE of $\lambda$. The 6 months survival by $F(6) = \exp(-6 \lambda )$.
On the linear scale, the variance estimate of $\hat{M}$ is $\hat{M}/\sum P_i$ where $$P_i = 1-\exp\left(T_i \log(2) / \hat{M}\right).$$
A symmetric interval for the median with this variance approximation is called the Bartholomew interval. However, most reported intervals will be asymmetric based on the variance stabilized interval. As a pragmatic solution, I'd recommend taking the midpoint of these estimates to recover the linear variance approximation. With an estimate of the variance, the remaining details can be recovered via the $\delta$-method.
The mapping $f(x)$ defined by $\exp(-6 \log 2 / x)$ gives $F(6)  = f(F^{-1}(0.5))$.
And
$$f^{\prime}(x) = 6 \log (2) \exp(-6 \log 2 / x) / x^2$$
So by the $\delta$-method, a consistent estimate of the variance of the 6 month survival would be given by:
$$ \text{SE}(\hat{S}_6) = f^\prime(x) \text{SE}(\hat{M})$$
The approximation seems to work well for $M$ and $S(6)$ not close to 1 or 0. R code below:
<code>set.seed(123)
x <- rexp(1000, 1/10)
d <- rbinom(1000, 1, 0.5)
f <- survfit(Surv(x,d) ~ 1)
sumf <- quantile(f, 0.5)

## median and SE median
med <- sumf$quantile
semed <- ({sumf$upper -sumf$lower}/2)/1.96

sixmo <- exp(-6*log(2)/med)
sesixmo <- 6*log(2)/med^2*exp(-6*log(2)/med) * semed

plot(f, xlim=c(3, 9), ylim=c(0.6, 1), xlab='Time', ylab='Survival')
title('Midpoint variance approximation for median to 6 month survival')
points(6, sixmo, cex=3)
segments(6, sixmo - 1.96*sesixmo, 6, sixmo + 1.96*sesixmo)
legend('topright', pch=c(1,-1), lty=c(0,1), pt.cex=3, c('Estimate', '95% CI'))
</code>


I downloaded a 32 bit program on a 64 bit system

Question: Did not notice until already running, downloaded a 32 bit program on a 64 bit system. Would I get better results installing the 64 bit program, or keep the 32 bit program and run it?
Comment: That's going to depend on the program, and specifically what system components (e.g., DLLs) it interacts with. As an example, you wouldn't want to install the 64-bit version of Microsoft Office if you want to use many add-ons; most add-ons haven't been rebuilt to be compatible with 64-bit Office.
Answer: There is no harm in running a 32 bit program on a 64 bit system.  More than likely you will not even notice a difference between a 32 and a 64 bit version of the program.  The biggest advantage of 64 bit programs is the ability to use more than 2GB of memory.  Unless your application is memory hungry, there is no need to upgrade.  Also, in some rare cases, 64 bit applications can run slower than 32 bit applications.


Why singleton Store in Flux can cause issue for server-side rendering

Question: I was reading the following sources Why use Redux over Facebook Flux?, the redux documentation http://redux.js.org/docs/recipes/ServerRendering.html as well as the definition of a singleton. Could someone explain how the store being a singleton in Flux causes problems for server-side rendering using Flux architecture with react?
Answer: Singleton are classes which can be instantiated once. On client-side, each user will have its own store but on the server there will be 1 instance of the store shared for all users....where we need an instance for every request.
e.g: if i have a cart where i got only one item, on serve-side, the store will have 1 item and all users will share the store and state in it.
Here is an answer
https://discuss.reactjs.org/t/facebook-flux-singleton-store-and-server-side-rendering/5652


When creating an anonymous class must I include the methods of the extended class regardless if abstract or concrete?

Question: When we use this new A() {};, if A is concrete and not abstract, do we have to include the methods of A? What if A was an interface? Do we have to include the methods of A? Why?
Answer: Whether a class is anonymous has nothing to do with whether you must include the methods of the extended class or of the implemented interface.
If A is concrete, then you don't have to override any methods.  You can override them of course, and you should override at least one of them, or else having an anonymous subclass is useless; you could use A directly.  You can supply your own new methods, although they won't be callable directly.
If A is abstract or an interface, then you must override all abstract methods, just as with any other named concrete class.
One should use the @Override annotation on all methods intended to override a superclass or implement an interface, to ensure that typos don't result in a method that doesn't override anything.


Unable to edit /etc/apt/sources.list file

Question: When I try to edit my sources.list file using the command:
$ gksu gedit /etc/apt/sources.list

It requests an administrative password and when I type the password, It says incorrect and try again.What to do? I am new to Linux and Ubuntu.
Comment: Are you using your current password? If so, does your account have administrative privileges? Welcome to AskUbuntu.
Comment: Yes,Iam using my current password and account with administrative privileges. bty using nano editor has resolved my problem. Thank you.
Answer: Use the default terminal text editor program nano instead of gedit to edit /etc/apt/sources.list. Open the terminal and type:
sudo nano /etc/apt/sources.list

Alternatively you can also replace sudo nano /etc/apt/sources.list with sudoedit /etc/apt/sources.list. Because nano is the default terminal editor in Ubuntu the two commands do exactly the same thing.
The instructions for using nano are always displayed at the bottom of the page. Use the keyboard combination Ctrl + O and after that press Enter to save the file to its current location. Use the keyboard combination Ctrl + X to exit nano.
Comment: Unnecessarily wasted 2 hours of time. Resolved.
Answer: gksu is probably set to use su instead of sudo as the authentication method. Therefore, it's asking you for the administrative (root) password.
To change this, run gksu-properties and choose sudo as the Authentication Method. This way, gksu will ask you for your password.

You'll notice that the dialog box that asks you for the password changes from:

which is asking for the administrative (root) password to:

which asks for your password to perform administrative tasks.
Comment: Yep, This is the reason. Got it.
Answer: Solving the problem:
If your root password is correct and you are receiving error from using gksu gedit /etc/apt/sources.list then use gksudo gedit /etc/apt/sources.list and go about the changes.
Comment: Why not use simple `sudo gedit /etc/apt/sources.list` ? When I do, it open gedit and let me edit the file.
Comment: @ Karel. No, it is gksu that is deprecated in Ubuntu 13.04 not gksudo.
Comment: I guess not. I have tried both out myself -- gksu doesn't work but gksudo works as against your launchpad link. It seems that gksu is deprecated in Ubuntu 13.04. It is clear that until you start using  pkexec gksudo is the right one to use.  There is no argument here though.
Answer: In kde you cannot open kate with sudo, ie # sudo kate <file>. Instead, you open the file normally, edit it then save. Kate then asks for your password.
Answer: Although I have been logged in as root user, the file was effectively not editable. Multiple editors took minutes to only display its content and none of the editors was able to write.
This is most likely to be caused by a swap file at the same location which is locking the file for editing.
In this case, backup the file, delete the original and re-copy the copy.
sudo cp /etc/apt/sources.list /etc/apt/sources.list.bak
sudo rm /etc/apt/sources.list
sudo cp /etc/apt/sources.list.bak /etc/apt/sources.list
sudo rm /etc/apt/sources.list.bak

You can also delete the file, create a new one and edit / paste the desired content into it, in case you have the text.


Do I need sensors to see real time data (speed and cadence) on Strava Live?

Question: I would like to see real-time data (speed and cadence, no heart-rate for now) on Strava Live on my iPhone 7. Do I need to install bluetooth sensors on my bike or it just magically works? If it just works, is it reliable/accurate or I should still install sensors and let it get this information from the bluetooth sensors?
Comment: To be honest - bluetooth is the wrong protocol for sensors.  ANT+ is far more economic on battery and works fine.  Bluetooth sensors use batteries 10 times quicker than the same ANT+ sensor, even BLE ones.   But iphones are only bluetooth- to get ANT+ you need an adapter, or a Wahoo RFLKT, a garmin, or  an android phone which do ANT+ natively.  Comment because not an answer.
Comment: My previous comment is now 7 years old, and the world's moved on.  BLE Bluetooth Low Energy improves battery life.  There now exist android phones without ANT++
Answer: Strava (Premium) can determine your speed using GPS data, although GPS can be less accurate than a dedicated sensor because it jumps around a bit.
There's no magic way to determine cadence without a sensor, except maybe counting it in your head.
Comment: iPhone has accelerometer, so it might be possible to help speed measurements using the data. If you keep the phone in pocket, it could be even possible to extract cadence from the data.
Comment: In the case of a fixed gear bike, you can determine cadence from speed and gearing information. So, you could in principle calculate it from the GPS data.
Comment: You may want to add a note that without a "STRAVA PREMIUM" subscription, you only see average speed / cadence data for your ride. If you want instantaneous real-time data, you got to pony up. :-(
Comment: That's a good point about the accelerometer. I'm not sure how well it would measure speed, since your acceleration is the same at a constant 5kph as at 25kph, you'd have to keep a running sum of all accelerations which sounds very error prone. Cadence is a good point, somehow an iphone by default measures your steps, but at that point the phone becomes the sensor. And since you can't see the screen, you couldn't see the live data anyway. And of course as far as I know Strava currently does neither of these (it does use the barometer for elevation though).
Comment: GPS speed is pretty accurate and consistent these days for reasonably steady state movement (e.g. road riding). It becomes an issue with fast direction changes e.g technical MTBing.  Iphone has gps for speed, accelerometer (and Gyros) with GPS could be fed into a Kelman filter, but GPS is dgoo enuf' for many, and sensors are accurate and cheap for the rest - not sure its worth the effort trying to do it without sensors.
Answer: My understanding and research are based only on cycling(amateur). Not sure but may be imposed on running too.
I use the Zepp app(Amazefit iOS app) and have Amazefit GTS Mini 2 (cheap heart rate monitor). There is no cadence sensor in my smartwatch or cycle. But still, my Strava showed Cadence surprisingly.
In my humble research, I found that cadence meters and phone accelerometers work similarly (if not the same). I started recording in the Zepp app and kept my iPhone in my pocket while cycling. I'm pretty sure the accelerometer in the phone measured the cadence.
In the below pic, you can see the cadence is flat when the speed increases. This confirms that I'm moving downhill and hence I have stopped pedalling altogether. The flats in cadence are averaging the overall cadence, it is just showing that value instead of a zero (if I don't pedal cadence = 0)

Now the zero/averaged cadence is either because I wasn't pedalling or the sensor didn't work. I had one more run where I attached the phone to the frame to check the map, in the below image, see the cadence is just spikes(not correct measurement) and averaged most part of it.

So to answer, the cadence can be measured by the accelerometer in your phone if it's in your pocket, strapped to your feet. or shin :D.
Strava doesn't use the accelerometer, so I imported the GPX file from Zepp and loaded it to Strava. This works pretty well.
Is the phone a replacement for a Cadence sensor? No, but looking at the data if it works and with an error of 5-10% I'm happy to use my phone.
Special thanks to the post - https://www.mtbr.com/threads/cadence-data-in-strava-without-sensor.1130685/
Answer: Answer: No you might not need external sensors in Strava, at least for running cadence.
Strava's cellphone app now has some support for phone internal sensors for cadence.  Some cellphones call it "steps per minute" or SPM or Running Cadence.
Nordic_HRM is a legitimate Bluetooth chest sensor, wheras Running Cadence is the internal sensor on this phone.

I got a month free of Strava premium and to my surprise there is now a cadence log from my run. It's a mess. Phone in shorts pocket, jogging I got very peaky readings between 130 and 175 spm, roughly the correct range. But doing mild intervals (73-77 per 300m) with walking rest, it gave 100-300 spm. I'm sure I never hit 200 even. Perhaps auto pause and bad logging logic made it worse.
I don't understand why the phone could not learn to pick up on the SOUND of foot steps. I bet it registers and is rythmical enough to be found in the mic data if only tried.
More info: https://www.mtbr.com/threads/cadence-data-in-strava-without-sensor.1130685/
Speed has always been available because it is calculated from GPS data.
Comment: Don't forget that Strava can probably infer *running* cadence from the phone accelerometers, but it has no means to measure *cycling* cadence on its own. Asking for access to the microphone would increase power drain, and don't forget that outdoors is noisy, so there would be an issue of signal to noise.
Comment: Hi, welcome to bicycles.  I believe the question was about _cycling_ speed and cadence, not running.
Comment: Welcome to the site - I'm going to tweak this answer a little in the [edit]  Feel free to modify further if I change your intent.


Is it preferable that a Muslim living in a secular democracy try to make it an Islamic state, rather than move to a Islamic state?

Question: In this question asking if a Muslim living in a democracy should turn it into an Islamic state, most of the answers seem to agree that the answer is yes, they should. But my question is, why is this preferable to simply emigrating to an already established Islamic state? Doesn't this allow the Muslim to live in an Islamic state as they desire, without having to impose it onto others?
Comment: The answers on that question actually completely miss one crucial nuance: the jurisprudence on this matter is different for Muslim majorities and minorities. Muslims living as a minority are under no obligation to "make it an Islamic state." Nowhere in the texts does it say to do that. The answer is different if they are living as a majority under a government not based on Islamic shari`a. In fact the precedent of Muslims living as a minority in Ethiopia peacefully and without political ambitions strengthens this argument. The obligation on minorities of course is to present the message.
Comment: I would question what does an Islamic state mean? Does it mean those which clearly state Shari'a as the source of jurisprudence, or simply any which apply Shari'a in parts of their jurisprudence.
Answer: Quran says:

لَا إِكْرَ‌اهَ فِي الدِّينِ ۖ قَد تَّبَيَّنَ الرُّ‌شْدُ مِنَ الْغَيِّ
  ۚ فَمَن يَكْفُرْ بِالطَّاغُوتِ وَيُؤْمِن بِاللَّهِ فَقَدِ اسْتَمْسَكَ
  بِالْعُرْ‌وَةِ الْوُثْقَىٰ لَا انفِصَامَ لَهَا ۗ وَاللَّهُ سَمِيعٌ
  عَلِيمٌ
There shall be no compulsion in [acceptance of] the religion. The
  right course has become clear from the wrong. So whoever disbelieves
  in Taghut and believes in Allah has grasped the most trustworthy
  handhold with no break in it. And Allah is Hearing and Knowing.
  http://tanzil.net/#2:256

According to this verse Muslims have no right to impose religion to others. But please note freedom of religion (beliefs) and establishing Islamic state have no conflict with each other. The best example is that many Jews and Christians and even idol worshipers were living freely at the same city of prophet and Muslims and prophet did not impose Islam to them. When an Islamic state is established there are some social laws made for people that all should respect them like laws in the any non-Islamic country but this does not mean all the people leaving in that Islamic state are imposed to accept Islam. They can be non-Muslim and believe in anything they wish but only should respect only to public laws of state. Anyway any state has some laws that is lined with basic ideologies of its rulers.
Another note is about duty of establishing an Islamic state. according to Islam when there are the minimum number of serious Muslim supporters required for establishing an Islamic state in a society, so establishing the Islamic state become obligatory for them. And if the mentioned number is less than the min. required it is not obligatory. This law has nothing to do with being majority or minority. But it depends only to determining that if there are enough serious supporters who can form the required power to establish Islamic state or not. Indeed such movements can have political dangers for Muslims living in such a society. So according to Quran if in a society exposing the beliefs can have danger of death for Muslim but has no benefit for Islam so the Muslim has the duty to hide his beliefs from public:

لَّا يَتَّخِذِ الْمُؤْمِنُونَ الْكَافِرِ‌ينَ أَوْلِيَاءَ مِن دُونِ
  الْمُؤْمِنِينَ ۖ وَمَن يَفْعَلْ ذَ‌ٰلِكَ فَلَيْسَ مِنَ اللَّهِ فِي
  شَيْءٍ إِلَّا أَن تَتَّقُوا مِنْهُمْ تُقَاةً ۗ وَيُحَذِّرُ‌كُمُ
  اللَّهُ نَفْسَهُ ۗ وَإِلَى اللَّهِ الْمَصِيرُ
Let not believers take disbelievers as allies rather than believers.
  And whoever [of you] does that has nothing with Allah, except when
  taking precaution against them in prudence. And Allah warns you of
  Himself, and to Allah is the [final] destination.
  http://tanzil.net/#3:28

Exactly same as what did messenger of Allah did at first 3 years after recurring his first revelation in Mecca and only secretly invited trusted people to Islam without having any public political movements. But when he found enough supporters he declared his movement against the pagan state of that time publicly that resulted in actions against messenger SAWW and Muslims and they became enforced to live out of city and Meccans were banned to have any relation with them even selling food to them. so some of Muslims died from hunger during those sanctions.
There are many laws in Islam like Jihad, religious tax, Qisas, Hadd, Diah, Amr bi Maruf, Nahy an Munkar,... that make it clear that it is impossible to practice Islam completely without establishing an Islamic state.
Please note in establishing an Islamic state Islam has problem only with heads of non-Islamic states who resist and fight against inviting their people to Islam and establishing Islamic state. But Islam has no problem with people if they accept or not accept Islam. According to Islam people should be always free in religion. But heads of states are different problem and should be deal with proper methods like the letter messenger of Allah Muhammad SAWW sent to Kings of two main superpower of world at 1400 years ago i.e. Roman Empire and Persian Empire the only two main power of that time. And finally if they do not accept Islam logically Islam has Jihad for such Kings and dictators who are enemy of God.
Also there is no room for liberal democracy in Islam and based on Quran state is only for God:

قُلْ إِنِّي عَلَىٰ بَيِّنَةٍ مِّن رَّ‌بِّي وَكَذَّبْتُم بِهِ ۚ مَا
  عِندِي مَا تَسْتَعْجِلُونَ بِهِ ۚ إِنِ الْحُكْمُ إِلَّا لِلَّهِ ۖ
  يَقُصُّ الْحَقَّ ۖ وَهُوَ خَيْرُ الْفَاصِلِينَ
Say, "Indeed, I am on clear evidence from my Lord, and you have denied
  it. I do not have that for which you are impatient. The decision is
  only for Allah. He relates the truth, and He is the best of deciders."
  http://tanzil.net/#6:57

In Arabic language the word for State is حکومت which its root is ح ک م and the word حکم in this verse is exactly the root for state and means: "The decision/command/government/judgement is only for Allah." The main function of state is decision making. And any decision in state or government which is not Islamic is rejected in this verse.
Please note Islamic democracy is completely different of liberal democracy. Islamic democracy means giving choice to people from options that all of them are previously qualified by Islam. but liberal democracy is giving the choice to people based on no limitation and only based on what their "self" with and want that mostly the with of this "self" is same as with of Satan because Satan has been very active for thousands of years and most of people are deceived by Iblis and Satans.

أَرَ‌أَيْتَ مَنِ اتَّخَذَ إِلَـٰهَهُ هَوَاهُ أَفَأَنتَ تَكُونُ
  عَلَيْهِ وَكِيلًا
Have you seen the one who takes as his god his own desire? Then would
  you be responsible for him? http://tanzil.net/#25:43
وَإِن تُطِعْ أَكْثَرَ مَن فِي الْأَرْ‌ضِ يُضِلُّوكَ عَن سَبِيلِ
  اللَّهِ ۚ إِن يَتَّبِعُونَ إِلَّا الظَّنَّ وَإِنْ هُمْ إِلَّا
  يَخْرُ‌صُونَ
And if you obey most of those upon the earth, they will mislead you
  from the way of Allah. They follow not except assumption, and they are
  not but falsifying. http://tanzil.net/#6:116
وَلَوْ أَنَّنَا نَزَّلْنَا إِلَيْهِمُ الْمَلَائِكَةَ وَكَلَّمَهُمُ
  الْمَوْتَىٰ وَحَشَرْ‌نَا عَلَيْهِمْ كُلَّ شَيْءٍ قُبُلًا مَّا كَانُوا
  لِيُؤْمِنُوا إِلَّا أَن يَشَاءَ اللَّهُ وَلَـٰكِنَّ أَكْثَرَ‌هُمْ
  يَجْهَلُونَ
And even if We had sent down to them the angels [with the message] and
  the dead spoke to them [of it] and We gathered together every
  [created] thing in front of them, they would not believe unless Allah
  should will. But most of them, [of that], are ignorant.
  http://tanzil.net/#6:111

Also movement of Imam Hussain a.s. at Karbala for making Islamic state shows it is highly needed. (Battle of Karbala)

References and further study:
Islamic Government
Comment: I have to disagree with one point. The question was "Should we move to Islamic State or try and change the secular laws to Islamic" and you mentioned "Movement of Imam Hussain ra at Karbala" as an example but I have to disagree because correct me if I am wrong but there was no other Islamic state besides the current one and Imam Hussain ra didn't have the choice to move to a Islamic State. (Correct me if I am wrong) but the questioner says they have the option to move to an Islamic State. Which is much better. No one has the courage to stand up against a country like our Imam ra did. So ...
Answer: The answer to this question depends on an individual's personal beliefs and perspective. Islamic teachings emphasize the importance of justice and the establishment of a just and equitable society. However, there is no specific directive in Islamic teachings that mandates Muslims to establish an Islamic state in a secular democracy.
In a secular democracy, Muslims have the right to practice their religion freely and participate in the democratic process to bring about change within the existing system. This may include advocating for policies that align with Islamic values and principles, such as social justice, equality, and human rights.
On the other hand, some Muslims may feel that moving to an Islamic state would provide them with a more supportive environment to practice their religion and live according to Islamic principles. However, it is important to note that not all Islamic states necessarily reflect Islamic values and principles in their governance, and that individuals should consider various factors when making a decision to relocate.
Ultimately, the decision of whether to work towards establishing an Islamic state in a secular democracy or to move to an Islamic state should be based on an individual's personal beliefs, circumstances, and the situation in their current location. It is important for Muslims to prioritize justice, compassion, and empathy in their actions and decisions, and to work towards creating a better society for all people, regardless of their religion or background.
To find out the difference between the two please follow the link: https://www.islamiqate.com/81/whats-difference-between-islamic-state-secular-democracy