Why/when should character conflict happen and how do I write it?

Question: I've come to the recent conclusion that my writing lacks conflict.
This problem is especially hard for me because I don't like conflict in my own personal life, and am the type who doesn't usually start conflicts and when faced with one, generally just yields so that it will end.
And I think I've probably projected this onto my characters a bit - they don't usually get in arguments or disagreements which leaves the whole book with a monotonous tone that really needs fixing.

Is there any way to know when conflict should happen, so it doesn't feel too sparse or conversely over burdened with drama.
Why should conflict happen? Is there a trick or formula to creating conflict?
Once I've figured out when and why, are there any rules to actually writing it?
Answer: Good question. I say so because I too struggle with this, for similar reasons. Even as a kid I would always feel frustrated when characters would argue and, even worse, split up because of these conflicts. Why can't they just talk it out and get along? I would ask. When the tension finally got relieved, so was I.
And even now, as an adult, I find it difficult to write it.
I'll start with the second bullet - why does it happen? Here are four reasons I find helpful in generating it in my own writing:

Limited "resources" - when a resource is limited, people will argue and fight over it. Don't let yourself focus on the obvious, like limited food. Think more abstractly - limited time will cause different people to act differently ("John thought to himself, 'I only live once, I'm not gonna miss the opportunity to go on this adventure.' Jane, his girlfriend saw him go out the door and felt deserted. All she wanted was to marry him and raise a family")
Pressure & different thresholds - different people have different thresholds for certain kinds of pressures. One person might crack under pressure while the other not, thinking that the first is overreacting.
History - similar to the previous bullet, as a motivating factor for it, a characters history guides their decisions. Imagine two people sharing a prison cell, one who has been in prison a dozen times, the other for the first time. One might feel an urge to attempt escape, the other prefer to wait for the trial (which wants which? you decide...)
Finally, and this is the deeper one, people have very different viewpoints and appreciate different traits. Does your character act from their gut, by instinct, or is he more cerebral?  (see here for some ideas on this: http://www.personalitypage.com/html/four-prefs.html) An old wizard might value taking time to work things out in his head before acting, seeing an immediate response as rash. His young female apprentice might see such behavior as boring, uninspired and instead seek more immediate action. Neither is wrong - both traits are important, some just work better in some situations. But the conflict is born from the different instincts people have.

Regarding how often it should happen - I don't have a formula. I think eventually you need to allow the conflict to drive both the growth of the characters and the progression of the story. There is no point in adding conflict for its own sake. What I've found in my writing is that whenever I add conflict, great things happen, new avenues for my plot open up (I'm a discovery writer), the characters change and grow, and I can leverage that one bit of conflict for a chapter or two without any need for more.
Finally - I think the tricky part in actually writing it is that you will usually have to choose one character as your viewpoint character for that scene, and for him/her you can describe their feelings and thoughts. The question is how to (a) show what the other side is thinking and feeling, and (b) how the viewpoint character interprets it. Does he/she understand the conflict for what it is, or are they confused, seeing only their own side?
One trick you could use that might help - write only the dialog and raw action between them, and then add the viewpoint emotions. I find that focusing on the externals first helps me focus the scene and make it feel more intense.
Answer: Conflict in a story arises from desire. The basic structure of any story is that the protagonist has a desire and there are forces or people who oppose their attaining that desire. The story proceeds as they attempt to fulfil that desire and face increasing obstacles leading to a moment of truth in which we discover just what they are willing to do to attain that desire, what they are willing to give up, how much they are willing to bleed.
Sometimes that desire is for something they don't have. Sometimes it is to retain something they do have that someone wants to take away from them. Sometimes in the course of the story they come to understand that something else matters more to them than the thing they thought was their greatest desire. But the basic arc of a story is formed by their desire, the things that stand in the way of that desire, and what they will do (or not do) to attain that desire.
Conflict comes from the forces that stand in the way of the protagonist attaining their desire. Conflict also comes when the protagonist must decide what they are willing to do to attain that desire, and the changes that may bring to their relationship with others. Conflict is not an incidental to spice up a story, therefore. It is of the essence of story. If there is no conflict there is no story because there is either no desire or nothing stands in the way of that desire -- or at least nothing that challenges the protagonist to stretch themselves to the limit to attain that desire.
At the same time this means that you don't have to do a thing to create conflict in you story. If you have the basic elements of story: the desire, the forces that oppose that desire, and the character of the protagonist who pursues that desire, conflict will inevitably fall out of character's pursuit of their desire.
Multiple characters may have their own story arcs, and sometimes the conflict may arise from the interference of one character's pursuit of their desire with another character's pursuit of their own desire. Multiple intersecting story arcs are often the sources of conflict in a complex work, but the basic formula is always the same: desire creates conflict between the protagonist and the forces that oppose their desire.
So, to your specific questions:

Is there any way to know when conflict should happen, so it doesn't feel too sparse or conversely over burdened with drama? -- Yes, conflict is the result of desire. Establish what your hero's desire is and what forces oppose that desire. Then start them on the quest to achieve that desire. The result is conflict. (At each step in the story, the hero will logically try the least costly thing they think might work, so conflict escalates through the story as they try more and more costly things, culminating in the highest cost they are willing to pay.)
Why should conflict happen? Is there a trick or formula to creating conflict? -- Yes, conflict is a result of desire and its frustrations. Find the desire. Find the reasons why that desire cannot be achieved. Bingo. You have conflict.
Once I've figured out when and why, are there any rules to actually writing it? -- No, conflict is a natural consequence of a hero pursuing their desire in the face of opposition. Find the desire, find the opposing forces, and march your hero forward. Given that your protagonist wants X, and given who they are, and given the the antagonist wants Y, which is incompatible with the protagonist attaining X, and given who the antagonist is, what does each of them do next.
Comment: I feel like your answer was directed more toward 'general conflict' and not 'character conflict' like I specifically wanted, however it was still exceptionally educational and I feel I learned a lot from it, so thank you for that! Take my +1.
Comment: @Celesol, all conflict is character conflict. Did you have something more specific in mind when you used the phrase "character conflict"?
Comment: Ahh, I suddenly see the error of my phrasing - I meant conflict between characters (as in two or more), not just conflict in general. Sorry about that!
Comment: Right, so conflict between characters comes from desire as well. But in the these cases you have to consider the desire of both parties. Characters are in conflict because their desires are in conflict. One person attaining their desire means the other person not attaining theirs. So again, you start with the desire, and the way that each person pursues their desire, and then put them on a collision course in which both desires cannot be achieved, and the conflict is what falls out of that encounter. It should be easy enough to write once you know exactly what is driving it.
Answer: conflict is always created when 2 people have a difference of opinions.  There is no magical formula or "trick".  It's a natural part of life and society.  To be without conflict means nothing grows, nothing improves.  Everything stays status quo because no one has an issue with the way things are.  Conflict is easy to generate.... 2 girls like the same guy, 2 guys like the same girl.  10 people are trying to get accepted for a job that has 1 opening.  Competition brings out conflict.  A teenager has to choose between sneaking out to go to a friend's party or staying home as their parents instructed.  Again conflict within 1 person is created.  Do you choose pasta or chow mein?  again an internal conflict is created.  It is hard to give advice without knowing your story.
You need to think about what is the overall goal of the story.  I hate watching sitcoms/tv  because they lack a broad story but rather each episode is a story separate from each other (for the most part) without an ending until the producers decide to take them off air.  Is your goal that the MC get's accepted into a top college?  Then maybe MC struggles in a critical class needed to be accepted or they don't have enough life experiences like in the movie 21.
Conflict doesn't always mean a fight but rather a road block that hinders MC from getting to the main goal.  Maybe MC wants to play basketball but is not good enough to make the team.  They have to practice to be good enough.  Maybe along the way in that story, they get a BF or GF who distracts them from their practicing which creates a side conflict and they have to choose between them or practice.
Get creative, think of the goal or objective of the story and then think about all the things that could prevent the MC from achieving that goal.  These conflicts can still easily fit into your "no fighting" mentality.  You just have to approach from a different definition of conflict.


Explaining how a magnetic field affects currents in a conductor, in the limit of high conductance

Question: Recently, I gave an answer to this question,
explaining my intuition on how much electric field impinges into
a good conductor under certain conditions, in order to reason about the limit of
perfect conductors. Partly because I criticized how the accepted
answer explained Gauss's law, and also perhaps because I accidentally interpreted the
(ambiguously worded) question as about a changing field, rather than a rotating conductor,
I received downvotes.
But I still want to understand whether my explanation has intuitive merit, so I'm asking the
trio of questions:

How does electric field look within a loop of conductive material when it is not moving itself
but is exposed to a changing external magnetic field?
How does the electric field look in the limit of infinite conductance?  For a superconducting
loop?
Does my explanation (in terms of eddy currents) lead to the right intuition? If not,
how should I revise my intuition?

A final thing I am curious about is learning more about the physics of superconductors,
as I chose not to be explicit in that case to avoid being incorrect.
There are several related questions asking about this issue, but the point of this question is to critique this intuition, not to answer the question without reference to it.
I apologize for its length, but my is explanation below:

The Maxwell–Faraday equation says $$\nabla\times\mathbf{E} = -\frac{\partial\mathbf{B}}{\partial t}.$$
Put roughly into English, this says: A changing magnetic field produces a swirling electric field that can accelerate charges around a loop.
Let's look at how a changing external magnetic field affects a conductor in the cases of a normal conductor, a "perfect conductor" (I mean this loosely, meaning in the limit of a normal conductor approaching infinite conductance), and a superconductor.
Normal conductor
In a conductor with finite conductance (a "normal conductor"), we already know the story that the a little bit of the electric field can penetrate inside and also induce a drift current in the bulk electrons. (I've made multiple answers on this sort of topic, so you can see some of my recent answers for intuition in this area.)
"Perfect" conductor
In general, we like to say a perfect conductor doesn't allow electric field lines in. This is a little inaccurate, first of all, because there are no perfect "normal" conductors, and second of all, because this catch-all explanation misses the important physics of why conductors typically cancel much of the incoming field, and why better conductors cancel more of the field.
Let's first take a step back.
What cancels (either all or most of) the electric field in conductors?
Main Process: Charge Build-Up
For most circuits, it all has to do with charge build-up somewhere in the material. In a conductor, charges move in response to whatever electric field penetrates, which usually often leads to an electrostatic case of essentially all the electric field being canceled in the conductor, even for the case of a normal conductor.
But a characteristic of this situation is that there is "an electromotive force," (EMF) which is fancy word for saying "we are consistently changing something about our situation that is not letting these charges settle in the way they normally do." Whenever we hear the term electromotive force, we typically should understand it as a summary of the actual forces and effects
that continuously push charges around a circuit.
For example, in a circuit, we have a battery. Charges move to attempt to cancel the electric field the battery produces, but  each the charges accumulate on the battery to try to alter the voltage on the terminals, the battery simply plucks that charge and puts it on the other terminal, sustaining the motion. (This act of restoring the charge to maintain voltage is due to a chemical process, which we
describe as producing an "EMF".) Thus in this case, there ends up being a steady-state of nonzero current in a conductor, and nonzero electric field in the conductor due to needing to overcoming the resistance of the conductor to sustain the current.
For the case of a battery, in the limit that that conductor is perfect, in order to completely cancel out the field, the charges still need to accumulate somewhere in the circuit, e.g. on a resistor. Now the electric field in the conductor will be essentially zero, but charges will still flow, keeping the momentum they initially had from being accelerated the instant the field wasn't zero in the near-perfect conductor.
In the case of electromagnetic induction, a changing magnetic field also produces an EMF due to Faraday's law. Charge confined to a loop would pushed around and around in a circle due to the swirling
electric field. But asking how much of the magnetic field gets into the conductor in the first place brings me to my next point.
What cancels (part of) a changing magnetic field in conductors?
Main Process: Eddy currents:
For this particular case, for a conductive loop exposed to a changing magnetic field, there will actually turn out to be another important effect: eddy currents. These occur because of Faraday's law: charges in a changing magnetic field want to swirl. They swirl locally in eddy currents then tend to counteract the magnetic field, and thus prevent some field lines from entering.
However, the case is precisely the same as before, in the sense that any resistance present prevents electrons from swirling fast enough to stop all entering field lines. So the external, changing magnetic field penetrates some distance inside, in any case; however, this penetration depth may become very small as the conductance approaches infinity.
Applying to the original scenario
@Orpheus was asking about a coil formed by a perfect conductor in a changing magnetic field. Let us simplify to discuss a simple loop.
The answer is simply: eddy currents in response to the changing magnetic field keep the changing external magnetic field relatively close to the surface, but it still penetrates some distance that decreases as conductance increases. The impinging, changing magnetic field still has a total EMF around the loop, and there is a swirling electric field (confined more and more tightly to the surface in the limit of high conductance) that accelerates charges around the loop. This acceleration around the loop ends when the external  EMF balances with the "reverse EMF" produced by accelerating electrons producing their own flux, but for finite conductance, the acceleration will end sooner because the resistance will help slow the electrons down.
You can also think of the net flow around the loop as one big eddy current, if you want. Now, let me explain some finer points about the previous paragraph in a few more words.
Since there is no resistor in the loop, there is no place for charges to build up to counteract the loop EMF from Faraday's law in the charge-build-up way. So the charges accelerate. This produces an magnetic field that curls around the loop, a back-action on the applied flux. But this flux also obeys Faraday's law, and produces a reverse EMF. Thus, electrons will continue to accelerate until the reverse EMF from this produced electric field equals the applied EMF.
The question is, does that equality ever occur? I might try to go back and do some calculations, but, in any case, this is already a bit of a trick question, because perfect conductors don't exist, so in fact charges don't continue accelerating forever, and instead the drag force from the non-zero resistance adds with the self EMF to balances out the applied EMF. However, in this case, we are using a drag force to balance out the EMF. This drag force is a phenomenological model we use because we don't want to model to microscropic electric fields in a material. If we still want to use our space-averaged electric field $\mathbf{E}$, we better keep this drag force separate from Maxwell's laws, and just include it as another force.
Thus, the electric field penetrates even a very good conductor with finite conductance, because before the self EMF stops the charge accelerations, self EMF + resistance does. But, as stated before, this penetration is confined tightly to the surface due to eddy currents, so the current is almost all on the surface as well.
Now we get to the fun part: superconductors.
Superconductors
Now, what is interesting to me is understanding how this works in the closest thing to a real-world perfect conductor, which are superconductors. I don't know much about superconductors, which have other properties like the trapping of magnetic flux lines inside of itself. Thankfully, how a superconducting loop responds to a applied magnetic flux has already been answered here on Physics StackExchange, for the case of a superconducting loop.
To paraphrase @Alfred Centauri's answer, the magnetic flux through a superconducting loop never changes; but to sustain this constant magnetic flux requires the current inside the loop to perfectly counteract any flux you try to push though. Because superconductors can only sustain a certain amount of current before becoming a normal conductor, this implies a high enough magnetic field will rupture superconductivity in the loop.
Note I make no mention of where in the superconductor this current is flowing, because I don't know much about superconductors. However, you should note that the case of superconductors already matches the intuition we gained from thinking about a limit of a perfect conductor: in order to stop accelerating, charges have to move fast enough to cancel the magnetic field.
Summary
Thus, to summarize:

In a normal conductor with fixed loop geometry, current in a loop flows only while the magnetic flux through the loop (from an external magnetic field) is changing, and dies after this applied magnetic flux stops changing, because the electrons will dissipate their energy due to the resistance of a loop. Eddy currents prevent this some of the external magnetic field from entering the conductor.
In a normal conductor with very, very high conductance, a penetrating electric field accelerates the charges, but the self EMF of the electrons is almost enough to cancel all of the electric field to stop the acceleration. Surface eddy currents prevent almost all magnetic field from entering the material. Because of this, the the loop current remains tightly confined to the surface, and can be thought of as a surface current. But because we rely on resistance a little bit to slow the electrons, some electric field must penetrate a shallow penetration depth.
In a superconductor, such flowing charges perfectly counteract the applied magnetic flux, and thus the flux through the superconducting loop is constant.

In at least in the first two cases, the electric field penetrates the loop a little bit; and we can use the second case to reason about the third. There is also a similar notion of penetration depth for superconductors, which may or may not match this intuitive notion of penetration. Also, note for a lot of the time when I talking about "stopping the acceleration," I mean for the case of a constant derivative of the magnitude of uniform applied global magnetic field.
Comment: Search up "London equations" and the meissner effect. This explains and derives the currents role in canceling out the magnetic field inside a conductor. (Although I think this assumes the conductor is infinite and thus there is no charge build up in any one location,*I think*)
Answer: Two relevant Maxwell Equations for isotropic materials are:
$$\mu \epsilon \frac{\partial \mathbf E}{\partial t} + \mu \mathbf J = \nabla \times B$$
$$\frac{\partial \mathbf B}{\partial t} = -\nabla \times E$$
For a normal conductor $\mathbf J  = \sigma \mathbf E$, where the conductance $\sigma$ has some finite value. If it is a continuous current, there is a static electric and magnetic field inside the conductor.
For a superconductor, $\sigma = \infty$, and the electric field must be zero for the same continuous current. That means: a loop of a superconducting material has current, magnetic field, but no voltage.
For a superconductor loop, where some alternating current is generated by an external changing magnetic field, the second equation tell us that there is an electric field inside the material. This is different from the previous case because now it is not a static magnetic field.
In the first equation all terms are also not static.
The reason because it is not possible an electric field inside a superconductor, with a constant current, is that the current would be infinite. But if the fields are not static, the Maxwell equations show that both E and B are indeed present.
Using the analogy electro - mechanics, mass is  inductance. Velocity is current and force is electric field. An oscillatory movement of the mass requires a changing force, even if there no damping (equivalent to no resistance).
And as for a mechanic oscillator, the maximum current corresponds to zero E-field, and the maximum E-field corresponds to zero current.
Comment: It seems my analysis also led to the intuition that charges in a perfect conductor continue to accelerate in a changing magnetic field until they cancel the changing flux. Although this did not really answer the question of critiquing the explanation I gave, thank you for sharing the mechanical analogy. I also wonder about any lag in this cancellation that comes from electrons being slow to accelerate.


Moderators ignoring flags

Question: For some reason the moderators have ignored my recent flags. My flags have not been declined, deemed helpful, etc. Is there a reason for that?
Answer: We do not immediately handle all flags.
No one is ignoring your flags.
Answer: Mariano is right. Nobody is ignoring your flags.
However, this is because nobody can see your flags any more unless they look directly at the flag history of a post and even then that's just a record of your flag, not an actionable thing.
You had a large number of flags declined (more than were found helpful). As a result, your flags are no longer shown to moderators and cannot be acted on either way.
At the moment there's unfortunately no way for you to recover from that.
Comment: Wow, really? There's no return from flag weight zero?
Comment: @Mad: that's been theorized - I don't know if anyone's actually been in a position to *test* it though.
Comment: @AsafKaragila Apparently not. In principle that makes sense - if someone's raising a lot of bad flags, we kind of want them to stop.  On the other hand, people can and do learn to flag better. Recovering from zero flag weight would probably require raising flags that can be seen and evaluated, which sort of defeats the purpose of zero flag weight. So I'm not sure right off the bat how best to approach changing this behaviour or if it should be changed.
Comment: Hmm. I think that one should use the review page to review automatically raised flags or so. Maybe that way to allow an increase in flag weight... but that sounds pretty impossible, almost all automatic flags are invalidated (not all, but the vast majority).
Comment: @AdamLear Wasn't flagging stuff that other users flag as well a way to recover flag weight?
Comment: This needs to be fixed.
Comment: Adam, why was I pinged now when you edited the comment?
Comment: @AsafKaragila Huh, no idea! I didn't think we notified on comment edits. Sorry about that.
Comment: Well, we do, but I'm not even mentioned in that comment! There's a bug report for ya!
Answer: Often when flagging it is the case that there are several open flags on the same post.
Moderators cannot clear just one flag, even if they acted according to the suggestion in the flag. In such cases moderators often keep the flags open in order to decide how to clear them.
(Note: I have never been a moderator, but I sure as hell flagged a lot. Roughly 950 flags - 780 accepted (and 120 disputed, most of which are invalidations).)

Moderators ignoring flags


Why isn't Radix Sort used more often?

Question: It's stable and has a time complexity of O(n). It should be faster than algorithms like Quicksort and Mergesort, yet I hardly ever see it used.
Comment: See here: http://en.wikipedia.org/wiki/Radix_sort#Efficiency The efficiency is O(kn) and it may not be better than O(n*log(n)).
Comment: Radix sort is frequently used in soft real-time systems such as games. Whether or not one algorithm outperforms another is, as usual, dependent on all the parameters of the problem, not just the complexity bound
Comment: @FrustratedWithFormsDesigner Perhaps the wiki has changed?  I don't see the reference to `n*log(n)* anymore, FWIW...
Comment: Boost has an (in place variant) of it: https://www.boost.org/doc/libs/1_62_0/libs/sort/doc/html/sort/sort_hpp.html but yeah, I think people just don't know it exists...either that or they all just use the "standard" sorting algorithm which, for whatever reason, framework creators tend to still re-use the "generic" sorts that aren't as efficient...maybe they aren't focused on sorting ints typically, since it's a rarer use case?
Comment: Link is now: https://en.wikipedia.org/wiki/Radix_sort#Complexity_and_performance
Comment: You may be confused by the fact that the sorting function in the C standard library is called qsort and not rsort. In reality, qsort will quite possibly not use Quicksort but whatever is most suitable - not in theoretical cases, but practical cases. And it's quite possible that radix sort doesn't work well for some key distributions.
Answer: That O(f(n)) really means in order of K*f(n), where K is some arbitrary constant. For radix sort this K happens to be quite big (at least order of number of bits in the integers sorted), on the other hand quicksort has one of the lowest K among all sorting algorithms and average complexity of n*log(n). Thus in real life scenario quicksort will be very often faster than radix sort.
Comment: Note on universality: Radix sort is fully capable of operating on floating-point keys, as well as variable-length integer keys
Comment: Note on the complexity stated: although (LSD) Radix sort has a complexity of O(n*K), this constant is usually small, typically chosen such that (2^(W/K))*C fits into L1, where C is the size in bytes of the counter, W the size of the key being sorted. Most implementations choose K=[3,4] for 32-bit words on x86. K can also be made adaptive to exploit temporal coherence (near-sortedness), as each radix is sorted individually.
Comment: This is a bit misleading: 1) "at least order of number of bits" should actually be "at most". For example, if you choose 8-bits wide digits when sorting 32-bit integers, presuming counting sort is used for each radix, it means 256 counting slots or 4 passes through the array to count and 4 passes to sort. That's K == 8 even if sorting millions of items. 2) Quicksort's "K" is actually log2(N) in the average case. Give a tiny 256-element array to Quicksort, and you will get K == 8 passes through the array on average, but ridiculous K=64 passes for the worst case.
Comment: The two major points of this answer are completely incorrect, but it's the accepted and top-voted answer. Is there anything we can do about this?
Comment: @rd11 feel free to write your own answer
Answer: Most sorting algorithms are general-purpose.  Given a comparison function, they work on anything, and algorithms like Quicksort and Heapsort will sort with O(1) extra memory.
Radix sorting is more specialized.  You need a specific key that's in lexicographic order.  You need one bucket for each possible symbol in the key, and the buckets need to hold a lot of records.  (Alternately, you need one big array of buckets that will hold every possible key value.)  You're likely to require a lot more memory to do radix sort, and you're going to use it randomly.  Neither of this is good for modern computers, since you're likely to get page faults like Quicksort will get cache misses.
Finally, people don't in general write their own sort algorithms any more.  Most languages have library facilities to sort, and the right thing to do is normally to use them.  Since radix sort isn't universally applicable, typically has to be tailored to the actual use, and uses lots of extra memory, it's hard to put it into a library function or template.
Comment: You need only `S(n) \in O(n)` space for sorting with radix, i.e. same as for heap or quick sort.
Comment: @SplinterofChaos has the wiki perhaps changed?  It doesn't seem to mention `n^2` for quicksort anymore, but `O(log n)` ...
Comment: I don't think it's "a lot" more memory, maybe 2*n (OK that's a lot more but maybe not impossible)? And the buckets are so small (assuming you're splitting on bytes and recursing) that it could fit well into cache?
Comment: @SplinterofChaos The O(n^2) memory is nonsense; even a bad implementation uses O(n) worst case. Sorting the smaller half recursively and the larger half directly takes the space down to O (log n).
Comment: Deleted my comment. Didn't want to be spreading misinformation and the edit button wasn't working.
Answer: I use it all the time, actually more than comparison-based sorts, but I'm admittedly an oddball that works more with numbers than anything else (I barely ever work with strings, and they're generally interned if so at which point radix sorting can be useful again to filter out duplicates and compute set intersections; I practically never do lexicographical comparisons).
A basic example is radix sorting points by a given dimension as part of a search or median split or a quick way to detect coincident points, depth sorting fragments, or radix sorting an array of indices used in multiple loops to provide more cache-friendly access patterns (not going back and forth in memory only to go back again and reload the same memory into a cache line). There's a very wide application at least in my domain (computer graphics) just for sorting on fixed-sized 32-bit and 64-bit numeric keys.
One thing I wanted to pitch in and say is that radix sort can work on floating-point numbers and negatives, though it's difficult to write an FP version that is as portable as possible. Also while it's O(n*K), K just has to be the number of bytes of the key size (ex: a million 32-bit integers would generally take 4 byte-sized passes if there are 2^8 entries in the bucket). The memory access pattern also tends to be a lot more cache-friendly than quicksorts even though it needs a parallel array and a small bucket array typically (the second can usually fit just fine on the stack). QS might do 50 million swaps to sort an array of a million integers with sporadic random-access patterns. The radix sort can do that in 4 linear, cache-friendly passes over the data.
However, the lack of awareness of being able to do this with a small K, on negative numbers along with floating-point, might very well contribute significantly to the lack of popularity of radix sorts.
As for my opinion on why people don't use it more often, it might have to do with many domains not generally having the need to sort numbers or use them as search keys. However, just based on my personal experience, a lot of my former colleagues also didn't use it in cases where it was perfectly suited, and partially because they weren't aware that it could be made to work on FP and negatives. So aside from it only working on numeric types, it's often thought to be even less generally applicable than it actually is. I wouldn't have nearly as much use for it either if I thought it didn't work on floating-point numbers and negative integers.
Some benchmarks:
Sorting 10000000 elements 3 times...

mt_sort_int: {0.135 secs}
-- small result: [ 12 17 17 22 52 55 67 73 75 87 ]

mt_radix_sort: {0.228 secs}
-- small result: [ 12 17 17 22 52 55 67 73 75 87 ]

std::sort: {1.697 secs}
-- small result: [ 12 17 17 22 52 55 67 73 75 87 ]

qsort: {2.610 secs}
-- small result: [ 12 17 17 22 52 55 67 73 75 87 ]

And that's just with my naive implementation (mt_sort_int is also radix sorting but with a faster branch of code given that it can assume the key is an integer). Imagine how fast a standard implementation written by experts might be.
The only case where I found the radix sort to fare worse than C++'s really fast comparison-based std::sort was for a really small number of elements, say 32, at which point I believe std::sort starts using sorts better suited for the smallest number of elements like heapsorts or insertion sorts, though at that point my implementation just uses std::sort.
Comment: Appears the mt_ are multi threaded implementations: https://softwareengineering.stackexchange.com/a/362097/65606
Comment: Always nice to hear the opinions of people with experience in the area.
Answer: It's quite rare that the keys you sort by are actually integers in a known, sparse range. Usually you have alphabetic fields, which look like they would support non-comparative sorting, but since real-world strings aren't distributed evenly across the alphabet, this doesn't work as well as it should in theory.
Other times, the criterion is defined only operationally (given two records, you can decide which comes first, but you cannot assess how a 'far' down the scale an isolated record is). So the method is often not applicable, less applicable than you might believe, or just not any faster than O(n * log (n)).
Comment: Radix sort can handle integers (or strings) in any range by recursively sorting them "a byte at a time" so they don't have to be in a sparse range FWIW...
Answer: One more reason:  These days sorting is usually implemented with a user-supplied sorting routine attached to compiler-supplied sort logic.  With a radix sort this would be considerably more complex and gets even worse when the sort routine acts upon multiple keys of variable length.  (Say, name and birthdate.)
In the real world I have actually implemented a radix sort once.  This was in the old days when memory was limited, I couldn't bring all my data into memory at once.  That meant that the number of accesses to the data was far more important than O(n) vs O(n log n).  I made one pass across the data allocating each record to a bin (by a list of which records were in which bins, not actually moving anything.)  For each non-empty bin (my sort key was text, there would be a lot of empty bins) I checked if I could actually bring the data into memory--if yes, bring it in and use quicksort.  If no, build a temp file containing only the items in the bin and call the routine recursively.  (In practice few bins would overflow.)  This caused two complete reads and one complete write to network storage and something like 10% of this to local storage.  Simply quicksorting the whole file would I believe cause about 2 * n log n reads and about half as many writes--considerably slower.
These days such big-data issues are far harder to run into, I will probably never write anything like that again.  (If I was faced with the same data these days I would simply specify 64-bit OS, add RAM if you get thrashing in that editor.)
Comment: @rogerdpack It wasn't that my approach used less space, it's that it used less access to the data.  I was sorting a file that was around a gigabyte while dealing with a compiler limit (this was DOS protected mode, not Windows) of a bit under 16mb of total memory use including code and a structure limit of 64kb.
Comment: Fascinating considering one of the disadvantages mentioned to radix sort sometimes mentioned is "it takes more space."  Still trying to wrap my head around this...
Answer: If all your parameters are all integers and if you have over 1024 input parameters, then radix sort is always faster.
Why?
Complexity of radix sort = max number of digits x number of input parameters.

Complexity of quick sort = log(number of input parameters) x   number of input parameters

So radix sort is faster when
log(n)> max num of digits

The max integer in Java is 2147483647. Which is 10 digits long
So radix sort is always faster when
log(n)> 10

Therefore radix sort is always faster when
n>1024
Comment: There are hidden constants in implementation details, but basically you're saying "for larger input radix sort is faster" which...should be the case!  It's just hard to find use cases for it but when you can...

Why isn't Radix Sort used more often?


Area Preserving Transformations from a Circle to an Ellipse

Question: I am looking for the class/set of transformations that map a circle to an ellipse while preserving the area inside.  Generally, maps of n-spheres to n-ellipsoids that preserve volume, if such a class/set exists.
Thank you,
Comment: If it takes all spheres to ellipsoids and preserves $n$-volume in the Euclidean space $\mathbb R^n,$ it is just linear with determinant $\pm 1.$ Plus a translation.
Comment: Thanks, to be sure then, I'm just interested in $SL(n,\mathbb{R})$?  If you write it up I'll check it as an answer, else I'll just up-vote the comment.
Answer: If it takes all spheres to ellipsoids and preserves $n$-volume in the Euclidean space $\mathbb R^n,$ it is just linear with determinant $\pm 1.$ Plus a translation, either before or after. So the basic object is, indeed, $SL_n(\mathbb R).$
If you relax either restriction you immediately get many more mappings. In particular, Moebius transformations on $\mathbb C \cup \{ \infty \}$ take any circle to a circle or line, any line to a circle or line. But area is not preserved unless you have $f(z) = \omega z + \beta,$ with $|\omega| = 1.$
Answer: There are a lot of volume preserving maps on $\mathbb{R}^n$. Here are a few simple transformations that preserve volume:

scale by $r$ along one axis and $\frac1r$ along another
rotation preserves distances and therefore volume
translation preserves distances and therefore volume

Combinations of these three transformations are enough to map any sphere to any ellipsoid with the same volume.
Answer: The folks in the animation business are always inventing new (and not-so-new) ways to do "volume-preserving deformations". Their idea is that preserving the volume of the object will make the deformation more "natural". It makes some sense -- when you flex your muscles, their overall volume doesn't change (I suppose). Anyway, if you google the term "volume-preserving deformation" you will find piles of stuff.
Generally, these deformations are only approximately volume-preserving, though. Good enough for animation, but maybe not good enough for your purposes. Only you can decide.
Answer: Any shear is an area/volume-preserving transformation.


Why is the ability of a virus to get crystallized considered as a "Non living feature of a virus"?

Question: My book states that the fact that :"Viruses can be crystallized" is a proof of their "Non living character"
Does that mean living things cannot be crystallized? If yes, why is that so?
Comment: Welcome to SE Biology. It is always necessary when quoting from sources in questions to state what the sources are. That way others can check the quotation is accurate, look at the context, and assess the credibility of the author. If you read the previous discussion of whether or not viruses are alive you will see that there is no recognized "touchstone" for life. Ability to be crystalized strikes me as one in a list of features where viruses are similar to non-living things.
Comment: Possible duplicate of [Why isn't a virus "alive"?](https://biology.stackexchange.com/questions/9438/why-isnt-a-virus-alive)
Answer: Crystallization involves removing extraneous molecules, so that remaining molecules — here, virions, or virus particles — can form a crystalline or ordered structure. https://en.m.wikipedia.org/wiki/Crystallization
As far as cells go, cellular proteins can be crystallized (some more easily than others), as well as nucleic acids, but having those crystals alone is not sufficient for life. You need an input of water, energy, etc.
Making crystals from the constituent parts of cells would effectively kill that lifeform. On the other hand, you can take virus crystals, add a bit of disorder, and they will "wake up" and regain their infectious properties.
Viruses sit on a fine line of what constitutes life. To some extent, the discussion is philosophical in that definitions are chosen and the subject either meets those criteria or not, and some criteria are a bit more arbitrary than others.
Some have argued that viruses in infectious virion form are life, at the stage when infecting a cell and redirecting its machinery to make more virus particles. https://www.ncbi.nlm.nih.gov/pmc/articles/PMC2837877/
Over the decades, biology has shifted from a study of cells in Petri dishes, or monks growing peas, to a more abstracted investigation into information science and related fields and subjects: mathematics, entropy, statistics, physics. That perspective started with scientists like Schrödinger, Turing, and Von Neumann, and it continues in the modern day with work by Dawkins, England, and others.
Viruses have and continue to shape the evolution of life around them. In a way, they are frozen information, and the definition of life may be changed over time, as we gain a more broader picture of how things work.
Comment: Another minor question would be whether all viruses tolerate crystallization. Do you know anything about that? I couldn't find much through a superficial search.


Energy based economy

Question: I am attempting to design an economy based around energy, namely, within a society possessing practical nuclear fusion. As I currently have it set up currency is backed by Hydrogen, meaning you could theoretically go to a bank and exchange all of your money for Hydrogen if you wanted to. Would this system work, and could things like superconductors also be used as a currency?
Comment: The problem with making the most common element in the universe a currency, is that it's the most common element in the universe.
Comment: Currencies backed by commodities went the way of the dodo about one hundred years ago, and for very good reasons. Why would you believe that in the future mankind will return to an idea which had its day in the sun and was eventually abandoned? (And hydrogen is *cheap*. It's about 1 USD per kilogram, compared to about 60,000 USD per kilogram for gold. For reference, 1 kg of liquid hydrogen is about 14 L or 4 US gallaundes. If you accept to be paid in hydrogen, bring a large tanker.)
Comment: How would a currency be "backed" by hydrogen?  Do all the nations of the world you're building have exclusive rights to all of its water?
Comment: don't bother with hydrogen, just base it on the kilowatt/ hour. that makes your base unit worth about 10 cents. or you can use kilojoules which would put your base unit at 0.3 cents of usd value.
Answer: A somewhat niche Sci-Fi (the "Meganesia" cycle) used aluminum for their currency. It is basically energy-based, as most of the cost of aluminum is the cost of electricity to produce it. Still, paper money is used. In a tongue-in-cheek for British pounds (of sterling, basically, pound of silver in the early days), they basically say that one local unit of paper money (I forget, how they called it) is basically worth of one kilogram of aluminum.
Answer: This could make sense in interstellar space where matter is rare.
I could imagine hydrogen being the basis for an economy in the outer Dark.  Matter is rare.  Aside from the people and the materials their ancestors brought, hydrogen is 99% of what there is.  People can work to accumulate the rarified atoms from space, or bring it great distances at substantial cost.
Hydrogen is the feedstock for the fusion generators that keep the lights on.  Hydrogen can also be fused into heavier elements and so replace some of the carbon, nitrogen etc that is lost to entropy.  Hydrogen is fungible and frangible and so can be the basis for the economy.
--
Why are these people out in the middle of nowhere, far from any solar system?  I admit I am curious.
Answer: Not practical
Abundance:  As various answers have noted, hydrogen is the most common substance in the universe.  Each water molecule is made up of two hydrogen atoms and one oxygen atom - if hydrogen becomes a currency then the ownership of every molecule of water and the multitude of other hydrogen compounds needs to be tracked in order to determine who has what money.  Remember that humidity is how much water is in the air at any one time?  Good luck tracking not just every millilitre of liquid water and every millilitre of air but also the humidity of each millitre of air in the entire atmosphere.  Remember to depreciate your assets when cooking and water vapor is rising from the pot of boiling water your pasta or rice is in!
Storage:  Hydrogen molecules are so small that it is difficult to store it without any leakage occurring.  Leak-proof storage containers are probably worth more than the hydrogen inside them would be.  The alternative is to store stable hydrogen compounds (eg water) rather than hydrogen gas itself, but then it means that the majority by mass of what you are storing is something other than hydrogen (eg hydrogen is only 1/9 the mass of the water).
Consumable commodity:  Making a substance that can be recycled (eg gold) a currency is not a great idea anyway in a modern economy, but making a substance that will be consumed in fusion reactors your currency is even worse.  I'll leave a full discussion of this to someone with more economic knowledge, but let's finish with a quote from the Golgafrinchans who arrived to colonise prehistoric Earth in The Restaurant at the End of the Universe:

"Since we decided a few weeks ago to adopt the leaf as legal tender,
we have, of course, all become extremely rich."...
"But we have also... run into a small inflation problem on account of
the high level of leaf availability, which means that, I gather, the
current going rate has something like three deciduous forests buying
one ship's peanut."...
"So in order to... effectively revalue the leaf, we are about to
embark on a massive defoliation campaign and ... er, burn down all the
forests..."
Comment: The basic meaning of the word "[commodity](https://en.wiktionary.org/wiki/commodity)" is anything that is traded in commerce. A more specialized meaning is any undifferentiated goods traded in bulk. Gold, silver, iron, aluminium, hydrogen, oxygen, argon, wheat, maize, soy, petroleum, coal, natural gas, electric energy **are** commodities. You cannot "make" hydrogen a commodity because it already is a commodity.
Comment: @AlexP thank you for pointing that out, I have replaced the word "commodity" with "currency" where appropriate in the last paragraph section
Answer: Any economy based upon an element is going to have trouble. As has been noted, hydrogen is abundant. But liquid hydrogen is not abundant at all, it requires energy, electricity, and machinery to produce liquid hydrogen.
if your fusion reactor requires liquid hydrogen to run, then your currency may be the equivalent of a gallon of liquid hydrogen. NASA used to pay 98 cents per gallon; but the price varies, so figure \$1 is equal to 1 gallon of liquid hydrogen. That weighs 0.2679 kg, so \$3.66 per kilogram of liquid hydrogen.
So you can,theoretically, go to your bank today and convert all of your money into full tanks of liquid hydrogen. I did not price out the tanks themselves, those are pressure tanks and much more expensive than their contents, but reusable.
That said, if you really want an energy-based economy, price everything in kilowatt hours. That is a more reliable measure of energy; and a kilowatt hour can be generated by numerous means; including humans peddling bicycles, focused sunlight boiling water for a steam engine, burning wood or coal to boil water for a steam engine, etc.
In the USA, the average price of one kilowatt hour is 12 cents, but it varies up to 40 cents depending on the area. It means 1000 watts applied for one hour (3600 seconds).
In electrical engineering we actually use Joules; which is a very tiny amount of energy, one watt applied for one second. So a kilowatt hour is 1000*3600 = 3.6 million joules, which is 3.6 megajoules.
Saying "Kilowatt Hour" instead of "Joules" is kind of like measuring distance by speed and time, like saying a town is 2 hours away at 50 miles per hour, instead of just saying it is 100 miles away.
But "kilowatt hour" is the better known term, and on most electric bills; so perhaps the more understandable term for lay readers.
Answer: 1 credit = 1 kilowatt/hour
If you want to base it on energy base it on actual energy.
don't bother with hydrogen, just base it on the kilowatt/ hour. that makes your base unit worth about 10 cents, or you can use kilojoules which would put your base unit at 0.3 cents of usd value, for story conversion purposes. Since this is fiction you can assume way more efficiency than current energy and make your base unit equal ot a kilowatt/hour. This way your currencies value is only effected by the efficiency of energy generation which as an whole changes slowly, thus is nice and stable. This also means currency is worth more on the frontier, which was often true.

Energy based economy


How to prevent all UPPERCASE body text?

Question: Some users enter body copy and comments with the caps lock on. All uppercase is considered shouting and I would like to convert it to lowercase or "natural" with uppercase characters at the beginning of a sentence.
Any easy solutions?
Comment: my site is live now, it's generating tons of "challenges", plus I have tons of ideas and my members come up with some too ;-)
Answer: Converting the post to all lower case would be pretty simple; you can implement your own filter like so:
function MYMODULE_filter_info() {
  $filter['allcaps_filter'] = array(
    'title' => t('Disallow ALL CAPS posts'),
    'description' => t('Rudimentary filter which converts all text to lowercase'),
    'process callback' => 'MYMODULE_allcaps_filter_process'
  );

  return $filter;
}

function MYMODULE_allcaps_filter_process($text) {
  // Attempt to make the first letter of the first word uppercase. This is very
  // likely to fail as the inputted string will probably be HTML.
  return ucfirst(strtolower($text));
}

Once you clear the caches you'll be able to add that filter to any text format you want.
It's worth noting that the description rudimentary in the comments is very, very apt...for example this will also convert any HTML attributes/tags to lowercase which might break embedded image paths etc. It might provide a good place to start though.
Constructing more naturally cased alternatives is going to be very tricky, mainly because you haven't just got text in there...you've got HTML as well. I can't think of a decent way to do this at the moment to be honest, short of importing the string into a DOMDocument and looping through every element, converting the text in chunks as you go.
I'd provide an example for that but I think you've got one ;)
Comment: I think CSS's `text-transform:capitalize;` would do what this filter does without [a|e]ffecting any tags.
Comment: @Jimajamma Yeah, visually `text-trasnform` would work even better than the above filter...but text would still come up in all caps in, for example, SERPs. This might be fine though, you should probably put that as an answer
Comment: thanks guys. Looks like I could create a lot of headache downstream if it's not implemented right. I think what I'm going to do is add a Capslock detector on my input forms and then display a message to the user why they shouldn't use all uppercase: http://code.stephenmorley.org/javascript/detecting-the-caps-lock-key/  Thanks again!!!
Answer: As alternative to the Clive solution, I would implement different hooks, which are hook_comment_view_alter() for comments, and hook_node_view_alter() for nodes; you could also implement hook_entity_view_alter() that is called also for nodes, and comments.
There are some differences between the two approaches that needs to be considered.

Input filters don't get any information about the source of the text they are called to process; they can be called for a node body, a node content, a field content, or a view.
The following screenshot shows part of the settings for a "long text" field; when "Filtered text" is selected, the user can select the input format that is used for the field being written.

The following screenshot shows the settings the Views module has for a view header; selecting "Global: Text area" as header, these are the settings Views would present for the view's header.

In any of those cases, the input filter is not able to understand when it is called, and for what. If your purpose is just changing the content of nodes, and comments, an input filter is not what you should implement. If your purpose is to change every input given from users (independently from the roles they have), then you can implement an input filter, but consider that input filters can be used in contexts completely different from the ones you could know of. What done from the Views module can be done from any other module that accepts input from the users, and allows them to decide the type of the input format (between the ones they can use).
Differently, hook_comment_view_alter() is given some information about the comment being viewed, as those hook implementations are called with the following code. (See comment_view().)
  // Populate $comment->content with a render() array.
  comment_build_content($comment, $node, $view_mode, $langcode);

  $build = $comment->content;
  // We don't need duplicate rendering info in comment->content.
  unset($comment->content);

  $build += array(
    '#theme' => 'comment__node_' . $node->type,
    '#comment' => $comment,
    '#node' => $node,
    '#view_mode' => $view_mode,
    '#language' => $langcode,
  );

  // …

  // Allow modules to modify the structured comment.
  $type = 'comment';
  drupal_alter(array('comment_view', 'entity_view'), $build, $type);

The same happens to hook_node_view_alter() which is invoked by node_view().
  // Populate $node->content with a render() array.
  node_build_content($node, $view_mode, $langcode);

  $build = $node->content;
  // We don't need duplicate rendering info in node->content.
  unset($node->content);

  $build += array(
    '#theme' => 'node',
    '#node' => $node,
    '#view_mode' => $view_mode,
    '#language' => $langcode,
  );

  // Add contextual links for this node, except when the node is already being
  // displayed on its own page. Modules may alter this behavior (for example,
  // to restrict contextual links to certain view modes) by implementing
  // hook_node_view_alter().
  if (!empty($node->nid) && !($view_mode == 'full' && node_is_page($node))) {
    $build['#contextual_links']['node'] = array('node', array($node->nid));
  }

  // Allow modules to modify the structured node.
  $type = 'node';
  drupal_alter(array('node_view', 'entity_view'), $build, $type);

In both the cases, also hook_entity_view_alter() is invoked, and it gets a parameter saying which type of entity is being altered. hook_entity_view_alter() is probably preferable when the same code is used for more than one entity (such as nodes, and comments).
The output of check_markup(), which is the function used to get the output of an input format, is cached. With the actual code, the cache is not used for comments, as the function (whose declaration is check_markup($text, $format_id = NULL, $langcode = '', $cache = FALSE)) is called without its fourth parameter, such as in comment_submit().
if (isset($comment_body['format'])) {
  $comment_text = check_markup($comment_body['value'], $comment_body['format']);
}
else {
  $comment_text = check_plain($comment_body['value']);
}

This is not what happens with fields, where the code used is the following one. (See _text_sanitize().)
// If the value uses a cacheable text format, text_field_load() precomputes
// the sanitized string.
if (isset($item["safe_$column"])) {
  return $item["safe_$column"];
}
return $instance['settings']['text_processing'] ? check_markup($item[$column], $item['format'], $langcode) : check_plain($item[$column]);

The code that in check_markup() checks for values stored in the cache is the following one.
// Check for a cached version of this piece of text.
$cache = $cache && !empty($format->cache);
$cache_id = '';
if ($cache) {
  $cache_id = $format->format . ':' . $langcode . ':' . hash('sha256', $text);
  if ($cached = cache_get($cache_id, 'cache_filter')) {
    return $cached->data;
  }
}

When $cache is FALSE, $cache && !empty($format->cache) is FALSE too, and the cache is not used. This is what happens with comments, for example. For fields, it is the module implementing the field that decides when to use a cached value, or not. (In the case of the node body, it is used a cached value.)

As side note, when the input of a user can contain any UTF-8 code, it is preferable to use drupal_strlower(), and drupal_ucfirst(), which are coded to always work with UTF-8 strings. See the code of drupal_strlower() as example. (drupal_ucfirst() calls drupal_strlower().)
  global $multibyte;
  if ($multibyte == UNICODE_MULTIBYTE) {
    return mb_strtoupper($text);
  }
  else {
    // Use C-locale for ASCII-only uppercase
    $text = strtoupper($text);
    // Case flip Latin-1 accented letters
    $text = preg_replace_callback('/\xC3[\xA0-\xB6\xB8-\xBE]/', '_unicode_caseflip', $text);
    return $text;

Comment: thanks for the very detailed answer. Looks a bit too complex for my simple case but I did learn a bunch reading it!
Answer: QUICK AND DIRTY, or should I say quick and dirty....you could plug this logic into @Clive's filter....
    <?php

$text='This is a TEST of the EMERGENCY BROADCAST system.
This is only a test. Had this been an actual emergency, you would have been vaporized about 3 milliseconds ago.  this concludes this test.';

$input=str_split($text);
$output='';

$intag=FALSE;
$afterperiod=TRUE;
$aftercap=FALSE;

$numupper=0;
$total=strlen($text);

foreach($input as $t) {

  if ($intag) {
    switch ($t) {
      case '>':
        $intag=FALSE;
      default:
        $output.=$t;
    }
  } else {
    if ($afterperiod) {
      switch($t) {
        case '<':
          $intag=TRUE;
        case ' ':
        case '.':
          $output.=$t;
          break;

        default:
          $output.=$t;
          $afterperiod=FALSE;

          if (ctype_upper($t)) {
            $numupper++;
          }
      }
    } else {
      switch ($t) {
        case '.':
          $afterperiod=TRUE;
          $output.=$t;
          break;

        case '<':
          $intag=true;
          $output.=$t;
          break;

        default:
          $output.=strtolower($t);

          if (ctype_upper($t)) {
            $numupper++;
          }
      }
    }
  }
}

$shouting=$numupper/$total;

if ($shouting > .5) {
  return $output;
} else {
  return $text;
}

but this turns all caps to lower in the text except for those at the beginning of a sentence (assuming no newlines, tabs, etc) and ignoring any tags.  Additional logic could be added to look for only repeating caps etc.  ADDITION: But then again, it does this only if more than half the characters are uppercase....
Answer: text-transform:uppercase;

use this in css
Comment: this would actually do the exact opposite of what he wants :)

How to prevent all UPPERCASE body text?


Documents Privacy settings

Question: I have opened a modern team SharePoint for my department. The SharePoint is required to be public to everyone of the company except for one specific folder that needs to be accessed for view and edit only by a small team. The problem is that I cannot find a way how to make this folder private from the public and available to the team.
Answer: Based on your description, I understand that you want to set a unique permission for a folder.
Please refer following articles to achieve this.
SharePoint: Unique Permissions
How to give unique permission to a folder in SharePoint Online document library

Documents Privacy settings


Is there a way to activate Adsense based upon location?

Question: I have a cloth store that only works in my country, but It receives some traffic from other countries as well, those other countries are not useful at all, so I was thinking if there is a way to activate Adsense based upon location in order to take advantage of those visitors.
Answer: The easiest way to do this is through Google DFP.
Setup an account there and create a house ad where you add your Adsense code. Then you can choose the geotargeting you want for the ads.
Comment: I have submitted my application It's being reviewed, thanks a lot, I will see tomorrow if it works.


Fast Matlab Code for hypergeometric function $_2F_1$

Question: I am looking for a good numerical algorithm to evaluate the hypergeometric function $_2F_1$ in Matlab (hypergeom in Matlab is very slow). I looked across the Internet, but did not find anything useful. Does anybody here have an idea where to find a fast algorithm to compute this function?
Answer: There is Matlab source code for J. Pearson's master's thesis "Computation of Hypergeometric Functions". The thesis is a available as
http://people.maths.ox.ac.uk/porterm/research/pearson_final.pdf
and the Matlab code URL is http://people.maths.ox.ac.uk/porterm/research/hypergeometricpackage.zip (I cannot judge the code because I am working with Pascal/Delphi).
Comment: I will have a look at it, thank you
Answer: A while back I wrote some simple Matlab code to implement the Gaussian Hypergeometric function $_2F_1$: get it here. The code is based on the function's infinite sum representation, which means that it's only valid inside the complex unit circle, i.e., ${\mid}z{\mid} \lt 1$ (no analytic continuation is performed, but these transformations might be useful if you need to do that). It's much faster than Matlab's hypergeom function (and permits you to specify a tolerance), but you should confirm that it gives satisfactory results (especially for ${\mid}z{\mid} \approx 1$ where you may need to adjust tolerances or increase the number of iterations) in the regime that you're interested in. The code from J. Pearson mentioned in the other answer is nice for learning about various methods and may be useful in other parameter regimes, but it doesn't seem to written with performance in mind – though it may still be faster than full symbolic evaluation using hypergeom.
Another alternative is to more-efficiently evaluate Matlab's symbolic hypergeom itself. You can try my hypergeomq function (tested in R2016a and R2013b; may require modification to work in earlier versions). This function uses the same underlying compiled code, but performs some optimizations in the conversion from floating-point to symbolic math and back. The speedup for $_2F_1$ probably won't be very dramatic, but for other forms it can be significant (e.g., an order of magnitude speed up for $_2F_2$ in some cases).
Comment: thank you, i will give it try, although i probably can perform those results not before monday, but thanks in advance.


Do the abbreviations O, N, F mean anything on the electric meter terminals?

Question: I am trying to troubleshoot a dual-energy heating installation.  I found this diagram from the electrical company.  The terminals below the meter face are labeled O, N, F, 12, and VCA.  12 I think is 12 volts, VCA is alternating current.  These are in French so I'm guessing O, N and F are as well.  If it helps: two of these terminals should act like a thermostat and close the circuit at a certain temperature (not sure which two,that's what I'm trying to troubleshoot).  I'm not sure what the third one does.
Comment: Where are you on this planet?
Comment: Quebec; the English language diagrams often don't translate the abbreviations
Answer: The answer awoke me at 4am: It's a three way switch.  N = Neutre (neutral).  O = Ouvert (Open, this circuit is open in the diagram), F = Fermé (Closed, this circuit is closed in the diagram).


Do bridge load-sensors follow linearity?

Question: I have been using four half bridge load-sensors. After forming a bridge, the output of the bridge is fed into ADC(ADS1230). I'm using this load-cell. From the output of the ADC, I want to convert it into KGs simply by 'Slope-method', assuming the output of ADC to be linear. I only have to be confirmed that the load-cell behaves linearly or not when the huge weight is subjected to it.
Comment: The datasheet for your load cell should give you a linearity spec. I can't remember when I last saw one which was any worse than 100ths or 1000ths of 1% though, so I doubt you'll need to worry.
Answer: Yes, load cells are generally very linear; you can expect weight to map linearly to resistance within the cell's operating envelope.
Answer: the linearity is typically 0.2% over 0 to max rated load. Decide the ADC resolution based on ratio of full scale to short term stability. This means a 11 or 12 bit load sesnor. If you have a more resolution from the ADC replace the last few bits with 0. A high accuracy ADc when used with a low accuracy load sensor yields a low accuracy answer for load. And load sensors requiring 0.01% (13 bit) ADC are not made as one would hardly require it.


Is it wrong to reply to an interrupt result, correcting your mistakes, when you did not get to the next round?

Question: I had an interview, and I know I definitely could have done better. The company sent me the result thorugh e-mail, and as I expected, I did not get to the next round of interviews. Would it be so wrong if I reply this e-mail trying to point out how I would have improved? I would not give excuses, but recognize my mistakes and correct them somehow.
I want to have another opportunity, perhaps not for this time, but later some other time.
If it is wrong, then what could I say?
Answer: You could send them a thank you note like:
Thank you so much for interviewing me for the X position. I can see now that I should have done Y. I am still very much interested in working for your company, and will apply again in the future."
If they like what you write, they might reconsider, but don't expect it.
Answer:
Would it be so wrong if I reply this e-mail trying to point out how I
  would have improved?

It's not wrong.
A politely worded Thank You letter, thanking the interviewers for their time and consideration, could also point out how you would have improved.
It's possible that it might help a small bit, but it's probably not going to make a difference. Most likely it won't hurt.


Keeping the password when migrating users from MSAD to RHDS

Question: I need to migrate users from the aforementoned platforms and the ideal situation would be that the users continued to authenticate with the same passwords. Is it doable by just copying the hashes? If not what additional steps should be taken?
Comment: Don't. It would be better to take the opportunity to educate the users in creating good and memorable pass phrases (https://www.xkcd.com/936/) and have them practice by setting one up with their brand new account under the new security system.
Answer: Short answer: No, this is not possible.
Your options:

Intercept password changes with a DLL installed in the AD domain controllers. Many AD admins do not like this. Also it's slow depending on how long users' password are valid.
Intercept password authentication in an application where users enter their clear-text passwords. Slightly faster but 100% user coverage is not guaranteed either.
Force users to go through a password reset process on your RHDS installation.


What is the difference between Test Objects and Runtime Objects in QTP? Is the given explanation correct?

Question: On a blog about QTP, the following is stated:

"All software applications and websites are getting developed using many different components or small units (e.g textbox control in vb, input tag in HTML, webbrowser contorl in .net) which can be called as Objects.
Some of the properties can be changed during run-time. These are known as RO (Runtime object) properties. And some of them can not be changed. They are known as TO (Test Object) properties."

Is this explanation correct?
Comment: This explanation is not correct.

Please see my answer to [my own question here](http://stackoverflow.com/questions/8699160/what-is-the-difference-between-ro-properties-and-to-properties-in-qtp)
Comment: Thanks a lot Motti for the clarification. :)
Answer: To understand the difference between Test Objects and Runtime Objects, it helps to think outside the computer for a moment.
Imagine, if you will, that you're sitting at your desk, and you are thirsty.  But you can't go to the breakroom yourself to get a drink from the soda machine.  So, instead you grab an intern, give him some coins and send him to the breakroom to get you a drink.
This particular intern is very new, so you have to explain to the intern exactly what you want them to do step by step.
Your script is very simple:
1) go to "the break room".
2) go to "the machine"
2) insert coins into "the coin slot"
3) press "the Coke button".
4) bring the can back to you.

So, in your script, you have described some things.
"the break room" is the name of the room that contains the machine.
"the machine" is the name of the machine in the break room.
"the coin slot" is the name of a hole in the front of the machine.
"the Coke button" is the name of a button on the fronf of the machine.

Now, since this intern is so new, he asks you "How will I know those things when I see them?"
So, you have to describe "the break room" as "It's the last room down the hallway with the green door."
you also have to describe "the machine" as "It's the Red machine with lots of buttons on the right side"
you also describe "the coin slot" = "it's the long rectangular slot above all the buttons"
finally, you describe "the Coke button" = "It's the big white button with a Coke logo on it".
The intern writes down all these descriptions as a list on a piece of paper.  The intern now has a piece of paper with names and descriptions of things that you expect him to see when he gets to the break room.
So, next the intern actually walks to the break room...
he finds the machine ...
he finds the coin slot and puts in the coins...
he searches the controls for a big white button with a Coke logo, but he cannot find one.  So, he comes back to you.
"I could not find "the Coke button" as you described it," he says.  As it turns out, the buttons were recently changed, and now all the buttons have a black background.  You explain this to the intern, and he changes the description on his piece of paper.  You send him back to try again.
So, the intern walks back to the break room...
he finds the machine...
he finds the coin slot and puts in the coins... (the machine previously spit them back out automatically, and he got them back)
he searches the controls for a "big black button with a Coke logo on it", and he finds it, and presses it.
The machine dispenses a coke.
So, he comes back and delivers your drink to you.
Now, using the above story, it should be much easier to explain the difference between Test Objects and Runtime Objects.
The intern is your test tool - QTP.
Test Objects are just Descriptions of real objects that your test tool should look for, just the same way the intern had to search for real objects (or "things") on the machine.
The list of things on the paper that your intern wrote down is like an Object Repository.  Each description has a Name and the description.  The script has names, and QTP looks up those names and gets the description from the OR.  As an example, your instructions to your intern could look like this:
Room("the break room").machine("the machine").slot("the coin slot").insert-coins-into
Room("the break room").machine("the machine").button("the Coke button").press

Runtime Objects are the actual objects in your AUT, just the same way that there was a real physical machine, a real physical coin slot, and a real physical button to press to get a Coke.  In software testing, those objects aren't physical, but they are real.
You can programmatically read your description of an object using GetTOProperty.  Also, you can change the descriptions of objects by editing your Object Repository, or you can programmatically change the on the fly using .SetTOProperty() from within your code.  What this does is change the description of the object your looking for - for example, if you change the description from a Coke logo to a Sprite logo, then your intern would successfully identify the button for Sprite, and your script could work with no other changes, except that you'd end up with your intern bringing you a Sprite instead of a Coke.
While you can change the descriptions, you can't change the actual real objects any more than your intern can change the coke button from black to white.  However - once your intern FINDS the button - he can interact with the button by pressing it, looking at it, jiggling it, or smelling it.  He just can't change it to something else.  There is no SetROproperty method for objects, but you can GetROProperty, meaning once the button has been identified by it's size, color and logo, you can also ask your intern to tell you how wide it is, or if it has an "out of stock" indicator you can ask the intern to tell you if that light is on or not.
Hopefully this fully answers your question about the difference between Test Objects and Realtime Objects in QTP.
Answer:
Some of the properties can be changed during run-time

Above statement is not correct.
Test Objects are the objects that are stored during recording.
Run-Time objects are the objects that is displaying in your AUT while playback your script.
Comment: Actually, the above statement is correct - TOproperties can be changed during run-time.  ROproperties, however, cannot.


Google script insecure?

Question: For a couple of years a script is run in https://script.google.com, but now it is seen as an insecure app? Why? The service is provided by Google right? Third party?
Answer: Without knowing the actual script, I've no idea what it's source is.
However, Google has recently launched tighter controls on securing your account and is now looking at things that it wouldn't have looked at before. (I was advised to remove my account from an old phone and to disable an app password I haven't used in quite a while.)
If you trust the script, then you can go ahead and tell Google so. It probably won't ask about it again.
More information from the Google Blog: More transparency and control in your Google Account
Answer: script.google.com is a service provided by Google to create scripts by anyone that have a Google Account, so it could be used by third parties.
When we try to run a script Google will show an authorization request that shows what authorizations the script requires.
Nowadays, Google added another security layer, telling users if the script was reviewed by Google or not. Scripts authorized before the new layer was introduced could throw the security alert that is shown in the question, suggesting us to review those scripts that have access to our data.

Google script insecure?


converting my shop to 220v

Question: Can I convert my shop to 220v? My shop has 110v ran to it with no sub panel. I would like to add a sub panel to my shop and run 220v from it for my air compressor and 110v for my lighting. Or what is your take on buying a 5000 watt converter?
Comment: @Rob: shop equipment that requires 220V is likely to draw way more power than a standard 120V circuit can provide.
Comment: Thanks fellows, does anyone know what I need to do to make this work?
Comment: What about a 5000 watt 220-110 step up/down converter?
Comment: How much **power** do you need at each of 220 and 110 in your workshop, and what's the amp rating of the feed to your shop?    And, fo course, how much do you want to spend?  It might be cheaper to pay an electrician to extend the 220 feed to your main house over to a new panel in your shop.
Comment: There is very little chance of a 5000-watt transformer being a workable solution for your compressor.  Even a much lower-rated compressor draws more than 5000 watts when starting.  The cost-effective option is Tester101's answer below.
Answer: Sure.

Pull four appropriately sized conductors from the main panel, to the new shop panel.
Install a properly sized double pole breaker in the main panel, and connect the four conductors properly in the main panel.
Connect the four conductors properly in the shop panel, making sure the neutral bar is isolated from ground.
Install a grounding electrode system (if the shop is detached from the main building).
Bond the shop panel to the grounding electrode system.
Answer: What you actually want is useful power, which is measured in Watts (W) or more accurately VA (really), itself defined as Volts x Amps.  Common USA outlets can't deliver much power.

That step-up/down transformer is no help.  It can change voltage, but it can't change the amount of power the outlet can serve.
A sub-panel is a straightforward affair as Tester101 describes.  My only addition is to "think big" - get a much larger panel than you need.  Homeowners get stuck all the time when they run out of spaces in their panel.  More spaces in the panel are cheap - in some cases it comes with free breakers.
And if the routing is complex, consider conduit - this lets you pull any wires you might want in the future.

You can re-designate your circuit 240V without running any new wire.

Get a 240V 2-pole breaker instead of the 120V.
Put black tape on both ends of all the white wires, to redesignate it as a "hot".
Change every outlet to NEMA 6 type.
Change every hard-wired load to a 240V load.  Note that many lighting products made today are multi-voltage 100-277V.

At this point you will have nowhere to plug in 110/120V loads.  You can power them off that step-up/down transformer you mentioned, although 2000W is big enough.
Comment: A nit:  power is Volt-Amps whenever there's AC power with a phase shift.

converting my shop to 220v


Extracting extents of the map view in QGIS

Question: Status bar in QGIS can display min/max of x/y for extents of the map view when panning and zooming. How can these values be extracted and used in expressions? The manual's expression page doesn't seem to have variables for current map view extents.
Comment: Welcome to GIS.SE. You can use the python console with this command to extract the bounds of the map extent: `extent = iface.mapCanvas().extent()`
Comment: Thank you. Can this method be used in label creation?
Answer: Do you mean the extent of the canvas (the view in the main window)?
This can be accessed using the @map_extent variable in Expression Builder which returns a polygon of the current canvas map extent.
You can then use min_x(), min_y() etc. to extract bounding box coordinates for use in your labels, or to guide your label placement using data defined override.
See below for an example of labels that update based on the map canvas extent. The expression uses min_x(@map_extent) and min_y(@map_extent) and then the distance from the point $geometry to the SW corner of the canvas (make_point() of the min_x/min_y values).
Comment: Marvellous! I used `z_max(@map_extent) ≶ #` and it's working great. For the record, the order in the variable is `z_min()`, which is what you might want to change to in your answer.


Is the pressure of the gas identical to the static pressure of the liquid in the diagram?

Question: In my application the liquid would be tapped from a fast-varying flowrate, and I want to measure the static pressure change during this by measuring the air pressure above it. Will this work?
Comment: The image won't load. The error message is that the image contains errors.
Comment: @Fred Hi, does that help?
Comment: @Oliver_Waters: Perfect!
Comment: there is a small difference due to gravity (`rho g h`) . Unless the point you are trying to measure is a significant height below the top of the liquid that is probably negligible though.
Answer: Yes, the pressure will be identical (with some qualifications). If you think about it, the gas will compress until the force on the boundary between the gas and liquid are equal (i.e., the pressure). Even with a compressible liquid, this should also be the case. You will want to have a reasonable initial pressure for your gas, as well - it may not work as well if your gas volume shrinks to a very small size in response to a very high fluid pressure.
You will get some amount of gas dissolving into the liquid, according to Henry's law. I'm not sure whether that will be an issue with the fluid you are working with. The gas will evaporate out of the liquid / dissolve in response to the pressure increasing and decreasing.
How quickly the gas responds to the increase or decrease in pressure will be another question. It will depend on the gas you are using (based on whether it is monatomic, diatomic, molecular, etc - based on its capacity to store and release energy in various modes). It will also depend on the degree of fluctuation of pressure, as well as the temperature of the gas and the size of the volume pictured here. If either the gas or fluid are supercritical, or if the initial gas pressure is at a low vacuum, things will get weird, but as long as you stay within the regimes where ideal gas assumptions are relevant you should be fine.
One thing to note is that a big tap combined with a small chamber should reach equilibrium pretty quickly. You may want to be careful about getting into very high pressures though if you are designing the seals / shell for this pressure vessel. Using inert gases is obviously preferable. Additionally, if you're using a pressure transducer, you may want to fit it with a snubber to prevent damage from fluid hammer.
Comment: Hi Phyllis, that's a brilliant answer, thanks very much for your help.
Comment: The particular application is with a flow of blood, and trying to measure at 100Hz+ pulses through it, hence taking into account what you are saying, I think it is safer not to go this route. The blood can clog up sensors obviously, hence I thought this might be a solution to that, but it would take a lot of work to find the parameters for the effects you have mentioned. Thanks again!


Code Coverage Drop

Question: My production org had code coverage of 85% but suddenly dropped to 55%. We have written test for every class and we are up to 63%. Anyone else have an idea of why this dramatic drop occurred and why it has become so hard to raise the coverage back up?
Comment: Are you saying all tests are running succesfully ? My guess is some validation rule / newly required field is making existing tests fail.
Comment: I experienced similar things before, but I don't have an answer. Are you cleaning test results? Do you have many non/covered classes?
Comment: Clear your test history and then rerun and its some known issue.Not getting link to official doc but clearing test history should resolve
Comment: Yes all test are passing in the test execution. Also yes we have taken all those measures of clearing out the test and compiling all classes. Apparently there has been a change in how the calculate code coverage. If a class has zero coverage it counts every line regardless of its purpose as not covered. So we have worked to get every class we have covered to at least 75% covered. Still not sure why we can not get it up over 63%. Any ideas?
Answer: You can see what code is covered, and by what tests in the developer console.
If you go to Your name > Developer Console, to launch it, you can then execute all tests (unless you are already confident test results are already up to date.)

Once you have done this, in the bottom right corner there will be a list of each Apex class in your org, with it's coverage..

Double clicking a file name will load the file into the viewpane and should colourise it by blue/red for lines covered and not covered. In the top left of this pane is a drop down in which you can select "All tests" or the specific test that touched the file to see how it's covering it.

Using this you should be able to determine what is not covered, and/or what your tests are actually doing (if they are still passing) and get coverage back up!

Code Coverage Drop


Advanced CSV-to-SQLite converter

Question: I just wrote an advanced CSV parser that translates CSV to SQL(SQLite Compatible) statements, which are then inserted into the database. It translates variable names in the CSV to values defined in the script.
Example CSV
0,1,An empty black tile,${ASSET_PATH}/BlackTile.png
1,1,Grassy Tile,${ASSET_PATH}/Grass.png
2,1,Lava Tile,${ASSET_PATH}/Lava.png
3,1,Stone Brick Texture,${ASSET_PATH}/StoneBrick.png

The code
# Variables that are used in the CSV files
ASSET_PATH=~/spacegame/assets

# $1 - File to read. Named same as table to insert to plus .csv
# $2 -
function parseCsvAdv2Db {
    local oldIFS=$IFS
    local table=$(echo $1 | cut -d'.' -f 1)
    local ins="INSERT INTO $table$2 VALUES"
    IFS='|'
    while read line
    do
        # Preprocess the line
        local data=$(eval echo "$line" | \
            awk 'BEGIN { FS=","; OFS="|"; } { $1=$1; print $0; }')
        local tmpdata=\(
        for field in $data
        do
            tmpdata+="'$field'"
        done
        tmpdata+=')'
        ins+="$tmpdata"
    done < $1

    ins=$(echo $ins | sed -e 's/)(/),(/g' -e "s/''/','/g")
    ins+=';'

    sqlite3 $dbfile "$ins"

    # Restore state
    IFS=$oldIFS
}

parseCsvAdv2Db test.csv '(id,type,descr,path)'

Answer: Your CSV parse is somewhat simplistic, it assumes the comma's are "simple" (no quoted commas, etc. This is not a bad thing, just an observation, but it leads on to the next thing... the cumbersome splitting and rejoining of the field values using awk, etc. I have a confession to make here, I dislike using awk. To clarify, there are often simple ways to do things, and then there are times the simple routes are not enough. You don't need awk for the simple stuff, and you need perl, or python for the complciated stuff. I like the concept of awk, I just don't like having to know three tools when two is enough.
So, I immediately look at your code and think "simplify" it.
If you are using a simple CSV parse, you may as well do it all at once, and use a simple regex and expand your sed use....
I assume you are running on a reasonably recent linux version.

the basename program has the suffix argument: basename -s .csv file/to/test.csv will return test (the base name of the file with the suffix .csv removed).
you are tagged as bash so I will recommend here-strings instead of the echo commands you use. Instead of $(echo $1 | cut -d'.' -f 1) do $(cut -d'.' -f 1 <<< "$1"). It saves an echo.
you should have a shebang line #!/bin/bash as the first line.

So, to strip out all the awk, and more, I would have:
function parseCsvAdv2Db {
    local table=$(basename -s .csv $1)
    local ins="INSERT INTO $table$2 VALUES"
    local data=""

    while read line
    do
        # expand variable names inside the line.
        line=$(eval echo $line)

        # add parenthesis and quotes to the data.
        # Internal quotes still missing.
        data+="('$line')"
    done < $1

    # Add internal quotes, and add comma between value sets.
    data=$(sed -e "s/,/','/g" -e 's/)(/),(/g' <<< "$data")

    ins+="$data;"

    sqlite3 $dbfile "$ins"
    #echo $ins

}

By sacrificing the per-field parsing from awk you instead gain the simplicity of bulk modifications of the comma values using sed, to expand them to quote their respective values. Combined with adding the surrounding ('...') structure for each line, it just works....
Answer: First of all, it should be noted that this script would be vulnerable to  arbitrary command execution as well as SQL injection.  It might be OK if you trust the CSV data not to contain malicious shell commands or characters with special significance in SQL.
Several features make this code hard to follow:

Mixing Bash and AWK.  It should either be pure Bash or mostly AWK (with a thin Bash wrapper to invoke AWK with the right parameters).  Calling AWK like this, especially with one invocation per line, is both confusing and bad for performance.
What does the | character have to do with anything?  It seems to be a secret delimiter used for Bash-AWK communication.  That's bad: will a literal | in the data break the script?
If you are going to override IFS temporarily, use the set-this-variable-for-one-command syntax.
Why is there post-processing done using sed?
$(echo $1 | cut -d'.' -f 1) can be better expressed in Bash using ${1%%.*}.

A corner case is that the code generates a malformed INSERT statement if the CSV file is empty.
Suggested solution
# $1 - Name of CSV file to read. Table name is inferred from this by
#      dropping the filename extension.
# $2 - Optional (column, names) for the INSERT statement
# $dbfile - SQLite filename
parseCsvAdv2Db() {
    (
        local rec_sep="INSERT INTO ${1%%.*}$2 VALUES"
        while IFS=',' read -r -a fields ; do
            local field_sep=
            echo "$rec_sep ("
            for field in "${fields[@]}" ; do
                echo -n "$field_sep'$(eval echo "$field")'"
                field_sep=', '
            done
            echo -n ")"
            rec_sep=,
        done < "$1"
        echo ';'
    ) | sqlite3 "$dbfile"
}

Alternatively, define this function to do just one thing — generate the INSERT statement — and let the caller pipe the result: parseCsvAdv2Db test.csv | sqlite3 "$dbfile".
parseCsvAdv2Db() {
    local rec_sep="INSERT INTO ${1%%.*}$2 VALUES"
    while IFS=',' read -r -a fields ; do
        local field_sep=
        echo "$rec_sep ("
        for field in "${fields[@]}" ; do
            echo -n "$field_sep'$(eval echo "$field")'"
            field_sep=', '
        done
        echo -n ")"
        rec_sep=,
    done < "$1"
    echo ';'
}

Advanced CSV-to-SQLite converter


Turing Completeness of System Which Randomly Fails to Complete Calculations

Question: If one were to create a variant of a turing complete language which upon completing a calculation randomly changes the answer by one, would it be Turing complete? For example, say I had a Python implementation which, upon every variable assignment, with probability $\frac13$ decreased the value by $1$, with probability $\frac13$ increased the value by $1$ and otherwise kept the value constant, would it be Turing complete? This seems to be able to perform all of the calculations which Python is able to perform, just not reliably.
Comment: Depends on your definition, I guess; you'd have to explicitly deal with probabilities (which are not a part of normale Turing machines) and tell us what the output of such a machine is, formally.
Comment: Computability speaks about functions which assign to every input one output. So you would have to explain which is the function computed here. This seems to be difficult, because the very essence of your idea is that every input is assigned to several outputs - just the opposite of the definition of a function...
Answer: I've gone around and around on this one.  It would seem that we've landed on "No, it would not be Turing Complete, although we might be able to approximate it with a bounded probability of error on either accuracy or returning in finite time."
In your post, you said "just not reliably"... that is, in fact, a crucial part of the definition.  To be Turing-complete, we have to be able to exactly simulate a single taped Turing machine -- getting it right "sometimes" isn't any better than flipping a coin to determine if it's raining outside with "50% accuracy".
In the given example, you seem to suggest that the random failures only occur on assignment, not for other operations in the computer.  Does this affect assignments performed by the programmer alone, or internal assignments performed as intermediate steps by the compiler?  If it only affects assignments performed by the programmer, many programs could be written (in horrendously terrifying complexity and near impossible to debug) without creating and assigning any variables at all.  In this case, I suppose it would be similar to a Turing tarpit.
If the programmer HAD to assign variables, they should be able to use something in the vein of the old Heinlein "Tell me 3 times", assigning the variable in an array repeatedly (say 100 times, or until 3 distinct values have been saved) and then use the median value (since all values are x, x-1, or x+1, the median value, not median result, must be the correct one).  This would cut into performance HORRIBLY, but should, typically, arrive at correct values.  (In fairness to @DavidRicherby, I concede that we cannot ensure both that we arrive at an answer and that it is correct with 100% certainty; for a look at how we could arrive at 3 distinct values without additional assignments, consider the following approach:
<code># function sum : x,y $\rightarrow$ z
var a = x + y;   // first assignment, may be x, x-1, or x+1
var b = x + y;
while (a == b)
  b = x + y;     // if this loop finishes, b is now distinct from a
var c = x + y;
while ((a == c) || (b == c))
  c = x + y;     // if this loop finishes, c is now distinct from a and b
if ((a < b) && (b < c))
  return b;
if ((b < a) && (a < c))
  return a;
// repeat for the other combinations; there should be 6 total if statements.
</code>
)
If the compiler can introduce intermediate assignment operations that the programmer did not that also suffer from this drawback (say, at the end of every elementary computation), or if there are other operations affected by this glitch (the killer one in my above example being the comparison operators), then we cannot simulate a Turing-complete language (or machine) at any speed -- we will only be right 1 out of every $3^n$ times on average, where $n$ is the number of operations we can't correct for.
The Short Version of My Answer:
I can try to check for errors internally myself in the midst of computation, which may or may not work depending on the details of your system.  If I can't have or emulate a verifying system, then I cannot be Turing complete -- I'm just guessing at solutions.
Given that popular consensus is that such a verifying system implemented could not guarantee both returning in finite time AND returning an accurate answer, it would appear no, although we might be able to approximate it a reasonable percentage of the time.
Comment: Agreed -- if you've seen all three values, you know the middle one is the correct one, but you might have to wait an unbounded length of time to see all three. Also, how would you know you've seen all three? It's hard to imagine writing code to detect that without using assignments but, as soon as you use an assignment, _that_ assignment could store the wrong value.
Comment: This answer would be easier to follow if it were edited to avoid "edit:" and "update:" and just directly answer the question in an order that is easiest to read for someone coming here for the first time.  See http://meta.cs.stackexchange.com/q/657/755.  Tell us what the bottom line is, and then defend your assertion by proof or reasoned analysis; you can skip the back-and-forths and replies to comments and so on.
Comment: It's not true that the median of 100 values, each of which is $x-1$, $x$ or $x+1$ is necessarily $x$. There is no way you can possibly guarantee that assignments are done correctly. On the other hand, taking the median _does_ allow you to achieve significantly higher correctness probabilities than $3^{-n}$. Indeed, this is a standard trick for boosting the success probability of randomized algorithms, since it typically allows exponential boosting of the success probability with only a polynomial number of iterations.
Comment: @DavidRicherby I would agree that the median of the results isn't necessarily $x$, especially for small numbers of attempts.  If one could loop until three unique values are obtained, the middle *value* would have to be the correct assignment -- but because of probability, I suppose this would present a halting problem issue.  (Example:  If I did the calculation 100 times, and ended up with 87 copies of "3", 9 copies of "4", and 4 copies of "5", I would know that "4" is the correct value because is it in the middle, even though it is not the median of the assignments.)