What is the difference between a list and a pairlist in R?

Question: In reading the documentation for lists, I found references to pairlists, but it wasn't clear to me how they were different from lists.
Answer: Pairlists in day to day R
There are two places that pair lists will show up commonly in day to day R.  One is as function formals:
str(formals(var))

The other is as language objects.  For example:
quote(1 + 1)

produces a pairlist of type language (LANGSXP internally).  The principal reason why you would even care about being aware of this is that operations such as length(<language object>) or language_object[[x]] can be slow because of how pairlist are stored internally (though long pairlist language objects are somewhat rare; note expressions are not pairlists).
Note that empty elements are just zero length symbols, and you can actually store them in lists if you cheat a bit (though you probably shouldn't do this):
list(x=substitute(x, alist(x=)))  # hack alert

All that said, for the most part, OP is correct that you don't need to worry about pairlists too much unless you are writing C code for use in R.
Internal differences between lists and pairlists
Pairlists and list are different principally in their storage structure.  Pairlists are stored as a chain of nodes, where each node points to the location of the next node in addition to the node's contents and the node's "name" (See CAR/CDR wiki article for generic discussion).  Among other things this means you can't know how many elements there are in a pairlist unless you know what element is the first one, and you then traverse the entire list.
Pairlists are used extensively in the R internals, and do exist in normal R use, but most of the time are disguised by the print or access methods and/or coerced to lists when accessed.
Lists are also a list of addresses, but unlike pairlists, all the addresses are stored in one contiguous memory location and the total length is tracked.  This makes it easy to access any arbitrary member of the list by location since you can just look up the address in the memory table.  With a pairlist, you would have to jump from node to node until you eventually got to the desired node.  Names are also stored as attributes of the list proper, instead of being attached to each node of a pairlist.
Benefits of pairlists
One (generally small) benefit of pairlists is that you can add to them with minimal overhead since you only need modify at most two nodes (the node ahead of the new node, and the new node itself), whereas with a list you may need to re-allocate the entire address table with an increase in size (this is typically not much of an issue since the address table is usually very small compared to the size of the data the table points to).  There are also many algorithms that specialize in pairlist manipulation (e.g. sorting, indexing, etc.), but those can be ported to normal lists as well.
Less relevant for day-to-day use since you can only do this in internals, it is very easy to modify list from a programming perspective by changing what any arbitrary element points to.
Loosely related to the above, pairlists are likely be more efficient when you have highly nested objects.  lists can easily replicate this structure, but each list and nested list will be saddled with the extra memory address table.  This is likely the reason pairlists are used for language objects that very likely have a high nesting / element ratio.
For more details see R Internals (look for LISTSXP and VECSXP, pairlists and lists respectively, in the linked location).
edit: interestingly an experiment to compare the memory footprint of a list to a pairlist shows the pairlist to be larger, so the storage efficiency argument may be incorrect (not sure if object.size can be trusted here):
> plist_to_list <- function(x) {
+   if(is.call(x)) x <- as.list(x)
+   if(length(x) > 1) for(i in 2:length(x)) x[[i]] <- Recall(x[[i]])
+   x
+ }
> add_quote <- function(x, y) call("+", x, y)
> x <- Reduce(add_quote, lapply(letters, as.name))
> object.size(x)
7056 bytes
> y <- plist_to_list(x)
> object.size(y)
4656 bytes

Comment: @"hack alert" I get same empty named list with `list(x= substitute())`
Answer: First of all, pairlists are deprecated
pairlists are deprecated for normal use because "generic vectors" are typically more efficient. You won't ever need to worry about them unless you are working on R internals.

lists can contain named elements
Each element in a list in R can have a name. You can access each element in a list either by name or by its numerical index.
Here is an example of a list in which the second element is named 'second':
> my.list <- list('A',second='B','C')
> my.list
[[1]]
[1] "A"

$second
[1] "B"

[[3]]
[1] "C"

All elements can be indexed by its position in the list. Named elements can additionally be accessed by name:
> my.list[[2]]
[1] "B"
> my.list$second
[1] "B"

Also, each element in a list is a vector, even if it is only a vector containing a single element. For more about lists, see How to Correctly Use Lists in R?.

pairlists can contain empty named elements
A pairlist is basically the same as a list, except that a pairlist can contain an empty named element, but a list cannot. Also, a pairlist is constructed using the alist function.
> list('A',second=,'C')
Error in as.pairlist(list(...)) : argument is missing, with no default
> alist('A',second=,'C')
[[1]]
[1] "A"

$second

[[3]]
[1] "C"

But, as mentioned earlier, they are deprecated. They do not have any benefit or advantage over lists that I know of.
Comment: Here's something curious: although a standard list cannot hold an empty element, it can hold `bquote()` as an element.  For writing functions for arrays with unspecified number of dimensions, using `do.call("[", c(list(arr), ...))` is very helpful, where you may want the list of arguments to include `bquote()`.  I suppose `bquote()` basically allows `list` to do everything that `alist` can.  Any idea why a pairlist is called a pairlist?
Comment: @jangorecki I added the link you requested.
Comment: instead of `bquote()` it is probably better to use `substitute()`
Comment: I think it might be called pairlist because of the limitation in size (to three elements), for a language object you have and operator element (1st), and then a pair of argument (2nd, 3rd args).
Comment: I put a downvote, please provide a reference why pairlists are deprecated, I will turn it into upvote then. I haven't found any info in manual. It still seems resonable for a highly nested structures, or a metaprogramming where you operate on language objects.


Projection formula for flat morphisms

Question: Let $f\colon X\to Y$ be a flat morphism between two smooth projective varieties. Let $L$ be a locally free sheaf on $X$ and $\mathcal{F}$ a coherent sheaf on $Y$. How to prove $f_*(L\otimes f^*\mathcal{F})\cong f_*L\otimes\mathcal{F}$? I think it is a well-known result but I couldn't find a reference. You can assume $f$ is smooth and surjective if you want. Thank you.
Comment: Tag [0B54](https://stacks.math.columbia.edu/tag/0B54) gets pretty close, but not quite all the way there. Because $f$ is flat, you may write $f^*$ for $Lf^*$; because $Y$ is smooth quasi-projective, $\mathscr F[0]$ is perfect (you can find a finite locally free resolution). Because $L$ is locally free, you can write $\otimes$ on the RHS instead of $\otimes^{\mathbf L}$. This only leaves the derived tensor product on the LHS, but I don't see a reason why that should be usual tensor product in this situation. (This could be a way to look for a potential counterexample.)
Comment: By the way, this is true with no assumption on $f$ and $L$ (in fact, for any morphism of ringed spaces) if $\mathcal{F}$ is locally free.
Answer: Based on my comment, I constructed the following counterexample (which I believe is standard):
Example. Let $(E,O)$ be an elliptic curve, let $Y = E$ and $X = E \times E$, with $f \colon X \to Y$ the first coordinate projection. Let $\mathscr L = \mathcal O_{E \times E}(\Delta - E \times O)$, and let $\mathscr F = \mathcal O_O$.
Then $f_* \mathscr L = 0$, since $H^0(U \times E, \mathcal O_{U \times E}(\Delta|_U - U \times O)) = 0$ for every open $U \subseteq E$ as $\mathscr L|_U$ is a (fibrewise) degree $0$ line bundle that is not trivial.
On the other hand, $\mathscr L \otimes f^* \mathscr F = \mathcal O_{O \times E}$ since $\Delta|_{O \times E} = (O,O) = (E \times O)|_{O \times E}$. The short exact sequence
$$0 \to \mathcal O_X(-O \times E) \to \mathcal O_X \to \mathcal O_{O \times E} \to 0$$
gives a long exact sequence
$$0 \to \mathcal O_E(-O) \to \mathcal O_E \to f_*\mathcal O_{O \times E} \to \mathcal O_E(-O) \to \mathcal O_E \to R^1f_* \mathcal O_{O \times E} \to 0$$
since $R^if_* \mathcal O_X(-O \times E) = \mathcal O_E(-O)$ for $i \in \{0,1\}$ by the usual (derived) projection formula. Thus,
\begin{align*}
& & & & f_*\big(\mathscr L \otimes f^*\mathscr F\big) = \mathcal O_O \neq 0 = f_*\mathscr L \otimes \mathscr F. & & & & \square
\end{align*}
Remark. What's going on is that
$$Rf_* \mathscr L = \mathcal O_O[-1]$$
is not flat over $Y$ even though $\mathscr L$ is. There is a $\mathscr Tor_1$ term interfering in the derived projection formula of [Tag 0B54]. To see the above formula for $Rf_* \mathscr L$, use the short exact sequence
$$0 \to \mathcal O_X(-E \times O) \to \mathscr L \to \mathscr L|_{\Delta} \to 0.\tag{1}\label{1}$$
Since $\mathcal O_X(\Delta)|_\Delta = T_E = \mathcal O_E$, we get $\mathscr L|_\Delta = \mathcal O_E(-O)$. Note that $f$ induces an isomorphism $\Delta \to E$, so the long exact sequence of \eqref{1} reads
$$0 \to f_*\mathscr L \to \mathcal O_E(-O) \to \mathcal O_E \to R^1f_* \mathscr L \to 0.$$
Above we computed $f_* \mathscr L = 0$, so the map $\mathcal O_E(-O) \to \mathcal O_E$ is the natural inclusion, so $R^1f_* \mathscr L = \mathcal O_O$. $\square$
On the other hand, $Rf_* \mathcal O_X = \mathcal O_E \oplus \mathcal O_E[-1]$ is a complex of free modules, so the derived tensor product of the LHS of [Tag 0B54] is just a usual tensor product, as we saw implicitly in the computation of $Rf_* \mathcal O_{O \times E} = Rf_* f^* \mathcal O_O$ above.
Comment: Dear Remy, I think your counterexample is right and thank you. However, I am actually in a special situation that I demand the $L$ to be a torsion line bundle on an abelian variety. The $L$ in your example is not a torsion line bundle. In this case if $f_*L\neq0$, then the projection formula is true by base change theorem. If $f_*L=0$, then i don't know how to do it. I wish to prove that $h^0$ of $L$ restricted to each fibre would be 0 but I couldn't.
Comment: Even if $\mathscr L = \mathcal O_X$ I am not sure what to expect. For a smooth morphism in characteristic $0$ it is a highly nontrivial theorem that $R^if_* \mathcal O_X$ is locally free for all $i$ (uses Hodge theory), but in positive characteristic this is unknown as far as I'm aware. (Warning: in the case above the derived pushforward $Rf_* \mathcal O_X$ *splits* because this is true for $R\Gamma(E,\mathcal O_E)$, but in general it will be a little more complicated and you need to think about a spectral sequence for Tor as you filter $Rf_* \mathscr L$ by cohomological degree.)
Comment: That said, if your interest is specifically in characteristic $0$, then maybe the Hodge theory literature might be of help ― sometimes results for $\Omega^i_{X/Y}$ can be extended to torsion line bundles. I'm not super familiar with this, so I don't know any good references off hand.
Comment: Let's work with a fibration betweem abelian varieties over $\C$. It needs not to be complicated. When $L=\mathcal{O}_X$, then $h^0$ is always 1. And you will have that the projection formula is true for any quasi-coherent $\mathcal{F}$ by base change. See Qing Liu's book algebraic geometry and arithmetic curves Remark 5.3.21(c) for example. When $L$ is only torsion and $f_*L\neq0$, it's similar since in this case $L$ restricted onto fibre is trivial.
Comment: I think a more precise version well deserves a new question, so that other people can share their thoughts!

Projection formula for flat morphisms


An update from Jelly Bean fails at 30%

Question: I have a galaxy S3 SGH i747, Jelly Bean 4.3.  The update is downloaded but every time it attempts to update, it fails at 30%. What to do now?
Comment: Can you get the OTA from somewhere on the Web(Trustworthy source)? You can update the system via stock recovery then. It won't void your warranty. Otherwise, are you on wifi or data-pack while downloading the update. You may try Factory-reset to see if things works out better.
Answer: Im sorry, i dont think there is any other option. The KitKat update for Galaxy S3 on AT&T is only downloadable via OTA (Over The Air). You cannot update for some unkown reason, that is, unless you are willing to FACTORY RESET your phone in order to be able to update.
(there is another VERY COMPLEX WAY on fixing this, it will involve ADB, Rooting, Putting your phone at risk, and voiding your warranty.... So i would not reccomend that, but tell me if you STILL want me to tell you the other way. But please note that you would be putting your phone at risk.)

An update from Jelly Bean fails at 30%


Trivial knot with some crossing points

Question: Suppose $K$ is a knot diagram of a trivial knot with some crossing points. Then we know that there is a finite sequence of Reidemeister moves to transform $K$ to a trivial diagram (diagram with no crossings). Now I'm asking about the sequence ? Is there an example of such $K$ such that the Reidemeister moves which increase the number of crossing points must be involved in any sequence transforming $K$ to trivial? In other words, can we say that any sequence to eliminate the crossing points does not involve creation of crossing points? I know this is not true in general ( transform a diagram to a diagram with minimal number of crossings) but I wonder if it's true for trivial diagram
Answer: There is a diagram of the unknot such that any sequence of Reidemeister moves transforming the diagram into the standard diagram must increase the number of crossings. Here is an example due to Kauffman and Lambropoulou:

One can prove that the number of crossings must increase in any sequence by performing all available Reidemeister 3 moves and observing that there are no Reidemeister 1 or 2 moves available that decrease the number of crossings. An unknotting sequence for the diagram is below (also taken from the paper of Kauffman and Lambropoulou).
See this related discussion on MathOverflow.

Trivial knot with some crossing points


How do you teach a child to tie their shoe laces?

Question: What approach can you use to teach a child to tie their shoe laces? What approaches are known, and how long should it take?
Comment: Before you teach the kid, make sure you're clear on what knot you want to teach. The most commonly used knot for this purpose is a slipped square knot. You want to make sure not to teach the kid the slipped granny instead. This site has a nice explanation: https://www.animatedknots.com/square-knot There's a brief animation at the top, and if you scroll down there is a longer video that contrasts it with the granny. The "bunny ears" are a separate thing that make the knot easier to untie. This is what makes it "slipped."
Comment: Something that seemed to help my kid a lot is that I gave the shoelaces of one of my old shoes, which were pretty long. I could tell that it was difficult for him to make the loops whit his own shoelaces (he didn't have enough lace), so I decided to give him plenty of "room" and that helped him to figure out the movements to bend, twist and manipulate the laces. I think that he also saw the lace as something to play with and experiment, as opposed to a new task that he could not master (the learning part was "reframed" a little bit).
Comment: an autistic child can take a very long time to learn this, be patient. Teach one stage at a time and perform the as-yet un-taught stages yourself.
Answer: There is more than one way to do it. The two approaches below work for both children and adults. It takes about a hundred or so tries to fully master each approach, depending on the age and dexterity of the child. It is easier to practice with the shoe off and in front of you, as shown in the videos.

Terry Moore: How to tie your shoes | TED Talk: https://www.ted.com/talks/terry_moore_how_to_tie_your_shoes

Terry Moore found out he'd been tying his shoes the wrong way his
  whole life. In the spirit of TED, he takes the stage to share a better
  way.

NOTE: The above video shows how to tie the doubly slipped reef knot, instead of the less secure granny knot (also see below).

An Even Better Way to Tie Your Shoe Lace | Hanna Michaelis | TEDxCoeurdalene: https://www.youtube.com/watch?v=rqXZHA46wTU

In this talk by teenager Hanna Michaelis (and featuring her father
  Mark Michaelis as her mostly capable assistant), Hanna will describe a
  much faster way to tie your shoes.

SEE ALSO:
Shoelace knot - Wikipedia: https://en.wikipedia.org/wiki/Shoelace_knot

The shoelace knot is a doubly slipped reef knot [...]. [...] The loops are sometimes referred to as "bunny ears", especially when the
  knot is taught to children. [...]
There are several ways to tie a shoelace knot; each starts with the
  tying of a half hitch, and requires attention or some habitual
  mechanism for arriving at a knot that is an elaboration of the reef
  (or square) knot rather than of the granny (or lubber's) knot. If
  the bow is horizontal across the opening the bow is correctly and
  securely tied, but if vertical is likely to slip. One approach is to
  start by taking, in each hand, the end of the lace that emerges from
  the uppermost eyelet on that hand's side of the shoe; then passing the
  dominant hand's end under the other end, from front toward back, and
  dropping each lace on the opposite side from where it started; and in
  the finishing step again grasping the lace on each side with the hand
  on that side (perhaps taking time to note that because each end
  crossed over the shoe before, the laces have switched hands - or vice
  versa, the hands have switched laces) and again passing the dominant
  hand's end under the other end, from front toward back. [...]
Tying two consecutive right-over-left half knots (or two consecutive
  left-over-right half knots) produces, instead of a square-knot-like
  bow-knot, a much less secure version corresponding to the granny knot. This version will also produce asymmetrical slips; one pointing
  down, the other up.

(emphasis added)
Comment: The Terry Moore talk is awful. He never makes it clear what distinction he's trying to make (between a slipped square knot and a slipped granny), nor does he explain how he knows that, supposedly, everyone in his audience is doing it wrong (which is almost certainly not true).
Comment: I suggest to not even start with a shoe but with a thicker rope and something appropriate to tie it around. These days there could be a christmas present box or something :-) Such a rope can be untied easily even if tied with force and will provide more fun to try. If the child understands why the first step of the knot is not enough to hold but the second step is, pass over to a shoe.
Answer: I'm using this technique here which involves coloring coding a white lace to match up the areas and using a knot as a guide. Hope this helps,
https://www.youtube.com/watch?v=eN9LcG_4B74
Answer: My daughter isn't quite there so I have not tried this book, but I recently saw it and saved it for when we get there. It is a step by step illustrated book with left/right color coded laces built into the book. https://www.montessoriservices.com/red-lace-yellow-lace
No matter what, giving them somewhere to practice tying using a dressing board or similar item will make it easier for them to learn, as they can practice each step and movement more easily on a flat surface on a table rather than hunched over their shoes. Make it an activity to do alongside coloring or other things they like doing!


Is smoothing out an oven's on/off cycling possible with a pizza stone?

Question: Will adding something like a pizza stone smooth out the highs and lows of an oven's cycling (the switching the element off and on)?
Comment: For some reason I was thinking that the question was about turning on and off the oven while enjoying an evening out :D
Comment: What kind of things have you cooked where the cycling affected the outcome? How large are your oven's temperature fluctuations?
Comment: @FuzzyChef more like an exact duplicate? [Use of pizza stone in gas oven](https://cooking.stackexchange.com/questions/19969/use-of-pizza-stone-in-gas-oven)
Comment: Kinda sorta duplicate of this question:  https://cooking.stackexchange.com/q/19969/7180
Comment: Every dish responds differently to an oven.  If the cycling is a problem it's usually because of radiated heat from the element being too hot on the bottom of the dish.  You can fix this when it's a problem with just a metal cookie sheet or any other piece of metal that can act as a heat shield between the bottom element and the dish.  A stone would do something similar, but it takes much longer to properly come to temperature so you'd need longer preheat times doing it that way.  A cookie sheet is usually enough to let you skip the preheat since it stops scorching on the bottom.
Comment: This question specifically asks about temp cycling, something that's only mentioned tangentally in the other question.  It's also about electric ovens, whereas the other Q is about gas.
Answer: I've used pizza stones to even out fluctuations in two different ovens which had severe on/off temperature cycles. One oven was an older gas oven, and the other one an older electric oven.  In both cases, installing the pizza stones did indeed lower the amount of temperature fluctuation in the oven; in the electric oven, fluctuations went from +/-45F to +/-20F, which helped a great deal with cooking times.
For this to work, the pizza stone needs to be sufficiently massive to act as a heat sink; each of the stones I used were over 15lbs.  This will also cause the oven to take longer to heat up.
Pizza stones will also help even out random hot spots created by a bottom flame or element, but as @dbmag remarks, they won't do much, if anything, about top-to-bottom gradient.
Comment: If you're baking on the middle rack, with a pizza stone on both the top and bottom racks, it will take a bit longer for the middle rack to come to temperature, but provide the same heat shielding from both heating elements.
Comment: The oven would need to be tall enough to have 3 usable racks, though, which a lot aren't.
Answer: It will go some way to reducing the temperature fluctuations, and is usually done to mitigate the sudden temperature drop caused by opening the oven door when making something that wants a high temperature like a pizza.
The consequences of the oven cycling on and off tend to be felt more in terms of placement within an oven; if the heating element is at the top of the oven, say, then food at the top is more exposed to periods of high temperature. That wouldn't be necessarily resolved using a stone.
The fact that this isn't a common practice for everyday cooking, whereas other techniques like putting food on the middle shelf or covering with foil are common, suggests that there's not much need for this. But if you suspect the cycles are causing you a problem then by all means give it a go.


How to keep a bone in place when posing/animating

Question: I'm new to animating in Blender and trying to figure out how to keep a bone in place while posing for animation. My character is a monkey swinging vertically across a ledge of a wall. I want to keep the hand completely still, in place, while rotating the rest of the body from the arm. But every time I try, the hand moves along with the rest of the body. Is there some way to pin the hand in place during animation? Thanks in advance!
Answer: This is exactly the task IK was maden for: set an IK chain from the hand to the shoulder (and remember that you can animate the influence of the IK constraint, so you can use normal FK for the others portions of the sequence).
Comment: You were absolutely right and it worked like a charm. With a lot of studying, of course. So very grateful you took the time to respond. Thanks!


Which of these are more reactive: the lanthanides or aluminium?

Question: I am not sure whether to consider the standard reduction potential or ionisation enthalpy. Which of these are more reactive: the lanthanides or aluminium?
Comment: Reactive towards what?
Comment: That has not been mentioned.The statement says "Lanthanides are more reactive than aluminium,is this statement correct or incorrect?" and I believe it's pretty ambiguous to ask such a thing.
Answer: Since the lanthanides are neither in the same period nor in the same group as aluminium, comparision is actually not feasible. Factors like atomic size and effective nuclear charge tend to predominate such comparisions, rather than ionization enthalpy or reduction potential.
Bear in mind that due to presence of electrons in f-orbital for lanthanides provide poor shielding of electrons farther away from the nucleus. This poor shielding is due to the fact that f-orbitals are quite diffused in nature. Yet, we cannot say anything about reactivity of lanthanides when compared to aluminium.
If you are still a high-school student, I suggest you do not ask such hypothetical questions.
Comment: Well this was asked in our country's entrance examination and I had the same views as you. I felt it was quite ambiguous to compare them and probably there was some more in depth explanation which I did not know of.


How can I play Windows games on Linux?

Question: I have Elementary OS (Luna) installed. I want to play some famous Windows games, for example GTA. I also can't find some programs I used to use on Windows 7.
Is there a way to run Windows applications on Elementary OS?
Comment: Have you heard about "wine"?
Answer: Unfortunately, if there is one area that Linux is severely lacking in, it's gaming. Most big game companies have little to no interest in developing native Linux versions of their games, although there are some notable exceptions (discussed later).
Your best bet for playing big-name Windows-only games is PlayOnLinux, an easy-to-use wrapper around WINE (WINE is an "application layer" that makes Windows apps "feel" like they are running on Windows, when they are actually running on Linux, with varying degrees of success). Their game catalog includes titles like GTA 3, GTA 4, GTA San Andreas, Skyrim, and Need For Speed. These are not free downloads, of course, for you'll need to own a valid copy of each game, often including the CD/DVD or License Key. PlayOnLinux also supports a range of non-gaming applications as well, but I'd suggest looking for native Linux alternatives to common Windows apps before trying to run a Windows app through PlayOnLinux.
Another alternative is playing games that are actually made for Linux. Many great native Linux games can be found through the recently-released Steam for Linux (I believe it's in the Software Center). Yet another source for great indie games (with some big titles too) is the Humble Bundle, which usually has more then a few great Linux games for sale under a pay-what-you-want model. Lastly, check out the Software Center itself, and be ready to explore some lesser-known but still high-quality and often free games.
Gaming on any Linux distribution is all about keeping an open mind. If you want an OS where you can just drop a game disc into the CD slot and click install, then Linux is not the answer. If you're looking to be a serious PC gamer, maxing out your FPS and taking advantage of that expensive nVidia graphics card, then Linux is still not the answer. But if you're willing to put a little effort into "making it work" and dealing with a few hiccups along the way, then you'll have a pretty good gaming experience.

How can I play Windows games on Linux?


Augmented Reality Concept in iphone

Question: I want to know how to implement augument reality concept in iphone. I have seen the apis like wikitude , Layers and Unifeye sdk but i am not that much clear about the concept. If any one know please suggest me which api have to follow to develop and if possible provide me some documentation.
Answer: Augmented Reality usually uses a space-filling-curve to reduce the 2 to 3-Dimensional problem to a 1-2 Dimensional problem. Basically it is just a reordering of sub-divisions of the surface thus it makes it easier to query the database for any locations or items in range or it helps partitioning the surface at all. You want to look for Nick's blog about spatial index quadtree and hilbert curve. A good example of a sfc is also the internet-map from the xbcd-comic.

Augmented Reality Concept in iphone


BIBO Stability considerations for Transfer Functions

Question: So I was wondering if you have a system, consider it \$G(s)\$ and it has no initial energy i.e. \$x(0) = 0\$ for the initial condition. If the transfer function exhibits: pole cancellation, would it be considered stable. I know this is a common paradox in the discipline ,but with the knowledge of an already "energyless" system that will only respond to a simple input/output relationship. Does this actually affect the stability for controller purposes?
Answer: If \$G(s)\$ is an arbitrary transfer function it is BIBO stable if and only if it is linearly stable. The proof is simple. Let \$x(t)\$ be a bounded input and put \$x_0\$ as the least-upper-bound of \$x(t)\$. The Laplace transform gives
$$\frac{x_0}{s} > X(s)$$
hence
$$G(s)\frac{x_0}{s} > G(s)X(s)$$
hence
$$\mathscr{L}^{-1} \left\{G(s)\frac{x_0}{s} \right\} > \mathscr{L}^{-1}\{G(s)X(s)\}.$$
But since \$G(s)\$ is stable, \$\frac{G(s)}{s}\$ is also at least quasi-stable (has poles no further than the origin), so \$\mathscr{L}^{-1}\left\{G(s)\frac{x_0}{s} \right\}\$ is also bounded.
Indeed \$\mathscr{L}^{-1} \{G(s)X(s)\} \$ will be a linear combination of terms within a collection of exponentially-decreasing envelopes, so the BIBO-linear stability correspondence is actually quite intuitive.
Pole cancellation can be done while maintaining stability, but it's risky because closed-loop poles move from their open-loop position and modeling / control uncertainties can cause the zeros to move off of the poles. If you use pole-zero cancellation to delete unstable poles the actual positions of the poles and zeros may not quite align, and the response will be unstable. SO NEVER DO THIS!!! The initial energy does not matter, as your inputs will excite modes corresponding to every pole which is not completely cancelled. The recommended approach for unstable poles, as always, is to use feedback to stabilize them.
Comment: also, if there is pole/zero cancellation of unstable poles and the system is not completely observable, then all sorts of unstable hell is happening to internal states of \$G(s)\$ while not observed in the output.  not observed until those unstable internal states hit the power supply rails and the system goes non-linear, **then** you will see the trouble in the output.


Gradient Map in Illustrator

Question: Is there a way to create a gradient map effect in illustrator?
I tried different bledning modes but I cant get it to look the the photoshop version.
Thanks in advance for the help.
Comment: You want to add that effect to a raster image?
Comment: It may be possible to achieve some similar effect. However, it would *greatly* depend upon the artwork. The gradient map in Photoshop is really just a hue adjustment on a scale. That *can* be done in Illustrator (not with blending modes).
Comment: Manually build a gradient mesh over your art.
Answer: Not by default no. There might be some plugins to do this.
However it wouldnt really work eactly the same way as in a raster image, since vectors dont work exactly the same. I think we have a question on why a curves adjustment doesnt really seem to produce the same thing in vectors as in raster graphics somewhere.
Comment: any alternative way to achieve the same?
Answer: Yes, there is! I just found out as well. Here's what you gonna do:

create two rectangles, same size as your image and with the desired colors (can be edited later).
place your image on top of one of them and select both.
on the opacity panel, click "Make mask". It will convert your image into B&W and use the data to create transparency on your rectangle.
Place the new group on top of the other rectangle.
Voilà!

Now you may want to play around with the "Invert mask" option, depending on hat colors you chose. You can change the colors of the elements individually or selecting them all and using the Recolor button on the Properties panel.
Comment: This is *not* the same as a gradient map. This is more like a `Multiply` blending mode. (which you can do easily without the opacity mask - i.e. transparency panel) There's a vast difference between this and an *actual* gradient map. I'd suggest you look at a gradient map in Photoshop using an *actual* gradient and *not* a single, flat, color.
Comment: [For Comparison](https://i.stack.imgur.com/MA2gT.png) . In addition, add a third color to the gradient and the difference is [more apparent](https://i.stack.imgur.com/ms0sN.jpg)
Answer: There is a workaround using Illustrator documents inside Photoshop,
One of the reasons we need to use vector art is to maintain resolutionless edges on text, flat art.. you know.. vector outlines.
Complete your art in Illustrator. Grayscale is best if you can think ahead far enough.  Then PLACE it in Photoshop.  When it asks you whether you want pixels or smart objects, pick smart object.  This creates a link to the Illustrator document and keeps that work intact as is on the output side, with your gradient map effect.   Some blending modes in the parent document may not work, I haven't used this technique on documents with complex blending options in layers.

Gradient Map in Illustrator


Store data in a xml file in Magento 1.9

Question: I have a module that has some input fields in admin. One of the input is an ID that will use the same value every time, so I don't want to display that input in admin anymore to avoid changing or deleting it (i'm not the only one who has access to the admin panel). I talk to a friend and he tells me to put it in a configuration xml file and take it from there. It is possible to do that? How can I create a new xml file and take that value from there? Can anyone help me please?
Comment: Yes it is perfectly fine. If a question has an accepted answer, it will be highlighted in question list and search results, so any user looking for an answer will know that there is an answer to the question and it is accepted as correct answer.
Comment: You can also answer your own question and mark it as accepted answer. So it will be useful for other users.
Comment: I didn't know that. It is ok if I answer now and I delete my edit?
Answer: So, after I search on the internet for a couple of days I finally managed to resolve my problem.
First I created a xml file in etc folder that looks like this:
<code><?xml version="1.0"?>
<config>
     <appid>app_id_here</appid>
</config>
</code>
To take the id from the file I use this code:
<code>$configFile = Mage::getConfig()->getModuleDir('etc', 'Module_Name').DS.'file.xml';
$string = file_get_contents($configFile);
$xml = simplexml_load_string($string, 'Varien_Simplexml_Element');
echo $xml->appid;
</code>
I hope in the future this will help some people.

Store data in a xml file in Magento 1.9


What happens if i leave my homebrew to ferment for 14 days then boil and cool it to distill it?

Question: I have made "Lemon beer" using white granulated sugar, lemons and dry bread yeast. I had it in first fermentation for about 8 days then switched the container to second fermentation for a further 8 days. today i took it out to boil and cool to distill it but the fumes are really strong just a few whiffs and i feel drunk in the head already. Is this batch still safe to consume or should i toss it and start again?
Answer: First of all, welcome to HB SE.  Questions about distillation are usually not anwsered here, since it is not legal in many countries.
I would say that if you do not have the right equipment or knowledge, it can be very dangerous, do not take any chances.  Brewing beer is relatively safe, distillation not so much.
Comment: ^ This.
Distilling is both an art and a science. I would suggest reading up on some of the science, temperature control (and control of heads and tails) is necessary for a safe and drinkable product.
Answer: You said you boiled and cooled it to distill it. Unless you are leaving out a lot of steps, you didn't distill your drink, you just boiled it. Boiling a drink like this will reduce the alcohol content and change the flavour, as well as producing more alcohol fumes, which may be why it smells stronger now. It shouldn't be any less safe to drink than it was when you finished the fermentation.


Searching by query and location in Grails app

Question: I am using the searchable plugin in my grails application to search for "Offering" instances in the following way.
Search setup with following mapping in Offering class
class Offering {

    static searchable = {
        only: ['title', 'description']
    }

    String title
    String description

    Category category
    Location location

    BigDecimal price
    PricePeriod pricePeriod

    static belongsTo = [user: SecUser]

    static constraints = {
        title(blank: false, maxSize: 100)
        description(blank: false, maxSize: 10240)
        category(nullable: false)
        location(nullable: false)
        price(nullable: true, scale: 2)
        pricePeriod(nullable: true)
    }

    public String toString() {
        return title
    }

}

Call to searchable service
 def search = {
    must(queryString(params.query))
 }

 def searchResult = searchableService.search(search, params)

As expected this returns appropriate hits from the mapped properties of Offering instances. A collection of offerings
What I would like to do now is search not only by the search query but also the Offerings child element of location. Specifically the "locationName" field within the child Location instance.
So if I search by query "dinner" and location "Brisbane" I would like to get a collection of offerings matching "dinner" with a child location instance with the "locationName" property matching "Brisbane"
Any ideas on where to start to implement something like this using the searchable plugin?
Location class
class Location {

    String locationName
    Location locationParent
    String postcode

    static hasMany = [locations: Location]

    static constraints = {
        locationName(blank: false, unique: true)
        locationParent(nullable: true)
        postcode(nullable: true)
    }

    public String toString() {
        return locationName
    }
}

Thanks for your help
Answer: I think what you want to do is something along the lines of:
class Offering {

   ...

   static searchable = {
       only: ['title', 'description']
       location component: true
   }

   ...
}

and
class Location {

    ...

    static searchable = {
       only: ['locationName']
       location component: true
    }

    ...
}


How can I adhere tile to a painted wall?

Question: How do I get tiles to adhere to a wall which was painted with kitchen latex paint?  Paint has proved to be impossible to remove.  Was thinking of applying Zinsser Gardz to seal over as some of the paint is lifting slightly.  Would appreciate some advice.
Comment: If the paint is lifting, no primer will help with that. You *must* scrape any loose material off the wall before proceeding.
Comment: "Paint has proved to be impossible to remove" seems contradictory to "paint is lifting slightly" ... Unless you remove the paint, your tiles will be not be stuck to the wall, but stuck to the paint (for what that's worth).
Answer: If the wall surface is solid, free of contaminants, us a mastic and go right over the painted wall, after you scratch it up a bit with sandpaper to give the mastic a slightly rough surface to grip to.
This is presuming the wall is above a countertop not subject to getting saturated with water to affect the drywall backing.


ScrollPane Component required in library even though it is not being used by Parent Movie

Question: note: all as3 is written in CS4 and compiled for flash 10.
I have a parent movie that loads a separate standalone SWF movie. This standalone movie happens to use the ScrollPane component (fl.containers.ScrollPane), and it runs correctly when launched on it's own.
When I attempt to have a Parent movie load the standalone SWF, i receive a run-time error:
TypeError: Error #1009: Cannot access a property or method of a null object reference.
at fl.containers::ScrollPane/drawBackground()
at fl.containers::ScrollPane/draw()
at fl.core::UIComponent/callLaterDispatcher()
I understand that this error can be avoided by adding the ScrollPane component to the Parent Movie library. My question is why is this necessary? If the component is only used in the standalone SWF being loaded by the Loader class, why does the Parent movie require the component to be in the library as well?
Answer: Seems more like the ScrollPane is not initialised before it is referenced. Might be that the parent does not let the swf execute its initialisation code before use.


Can Interaction with the environment cause $|0\rangle$ to evolve into a superposition like $|+\rangle$?

Question: We say if a qubit is in state $|0\rangle$, and it is possible if it interacts with the environment it can result in a bit flip to a state $|1\rangle$, so I was wondering why can't it go to a superposition state instead? Is it possible? If not then why is it so?
Comment: It should be certainly possible by application of e.g. Hadamard gate. Application of gate is, in certain sense, also interaction with an environment.
Answer: If the qubit is in connection with an environment, most likely it will develop quantum correlations (entanglement) and will become a mixed state. If the state is pure, the most general state is a superposition of states for the qubit $|0\rangle,|1\rangle$ and those of the environment $\{|e\rangle\}$:
\begin{eqnarray}
|\Psi\rangle=\sum_{e}\left(\psi_{0e}|0,e\rangle + \psi_{1e}|1,e\rangle \right).
\end{eqnarray}
This is a pure state because the combined system qubit+environment is considered a closed quantum system itself.
To look at the qubit alone, we need to trace out the environment degrees of freedom and look at the reduced density matrix of the qubit:
\begin{eqnarray}
\rho_q=\text{Tr}_e |\Psi\rangle\langle\Psi|
\end{eqnarray}
This will yield in general a mixed state, unless the environment and the qubit are completely uncorrelated. The precise state of the qubit after interacting with the environment depends on the set of Kraus operators that describe such interaction with a bath. If the associated map for an interaction operation is a completely positive trace preserving one, then:
\begin{eqnarray}
\mathcal{E}(\rho_q)=\sum_i K_i\rho_q K_i^\dagger,
\end{eqnarray}
where $K_i$ are the Kraus operators describing the operation and satisfying $\sum_i K_i^\dagger K_i=I.$
For a bit-flip noise model, there are $K_0=I$ and $K_1=\sigma_x$ as Kraus operators, depending on some probability $1-p$ the state of the qubit will remain invariant under the map, giving:
\begin{eqnarray}
\mathcal{E}(\rho_q)=(1-p)\rho_q + p\sigma_x\rho_q \sigma_x.
\end{eqnarray}
This corresponds to a mixed state in general. It does not make much sense to talk about superposition state in an open system given that generally the state will have purity $\text{Tr}(\rho_q^2)<1$ due to interaction with an environment.
Comment: This might be a little off topic but can you tell me when we say tracing out the environment, so does it give us the density matrix of the principal system?
Comment: If you trace out the degrees of freedom of the environment, it gives the reduced density matrix of the principal system. However, quite generally this will correspond  to a mixed state if the environment and system interacted in some way. The way to know whether the stage is mixed is to look at the purity of the state, which is always less than 1 for mixed states.
Comment: got it thanks so much
Answer: It entirely depends on what "environment" and "interaction" you're talking about. As an extreme example, your "environment" could be a qubit in the state $|+\rangle$, and the interaction a SWAP gate, and then the interaction with the environment will send whatever initial state you had into $|+\rangle$. As a quantum channel, you model this as the mapping $\Phi(\rho)\equiv\operatorname{tr}(\rho)|+\rangle\!\langle +|$.
If you have error correction in mind, a more relevant example might be a channel that flips after a rotation, as suggested in the comments. That is, the channel $\Phi(\rho) = \frac12(H\rho H + XH\rho HX)$.
Generally speaking, any environment interaction that can be modelled by a quantum channel is in principle possible (tautologically so).


Why can't I bind tab to multiple spaces?

Question: I'm trying to bind tab to either a tab or multiple spaces in Latex/ESS-noweb mode but I can't get it to work. I tried (local-set-key (kbd "<tab>") 'self-insert-command) which didn't work, and then (local-set-key (kbd "<tab>") (lambda() (insert "   "))) which also didn't work.
Comment: See https://emacs.stackexchange.com/q/5579/15748 and https://stackoverflow.com/a/34835914/3084001. Your second example is missing an [`interactive` spec](https://www.emacswiki.org/emacs/InteractiveFunction), which makes it a plain function, rather than an interactive command. Functions must be interactive in order to be bound to keys. See https://www.masteringemacs.org/article/mastering-key-bindings-emacs for a great writeup on how to define and bind commands.
Comment: It would be helpful to clarify whether you are solely looking to insert some string of text, such as tab or space characters (which is covered in the questions I link), or whether there is a higher-level purpose to this, such as performing indentation or some other type of formatting, as suggested by your choice of tags. In this case people may be able to provide answers relevant to LaTeX/ESS modes.
Comment: 1. The function you are attempting to bind to a key is not a command. It is missing an `interactive` spec. 2. Only keys that correspond to characters can reasonably be bound to `self-insert-command`, so your first attempt would be wrong even if it had `interactive`: `(kbd "")` is not something that can be used by `self-insert-command`.
Comment: "which didn't work" carries very little information.  Please clarify.
Comment: @Basil Sorry for the lack of clarity. I'm new to emacs and wasn't aware of the command/function distinction. The higher level purpose is that I would like to adjust the electric indentation settings somehow, I'm just not sure exactly how I would like them yet.
Answer: (local-set-key (kbd "<tab>") #'tab-to-tab-stop)

Will make tab behave like it does in other primitive editors.


What is the probability of selecting all three colors when $4$ balls are randomly selected from a box containing ...?

Question: What is the probability of selecting all three colors when $4$ balls are randomly selected from a box containing $7$ black, $4$ green and $2$ yellow balls?
Comment: Hello @xxssxxdd, welcome to MSE. Questions in the style "here is the question, solve it" are not always well-received on MSE. Can you please add in the question what your attempts are?
Answer: you can use combination formula to find out:$$p(3C)=p(2B+1G+1Y)+p(1B+2G+1Y)+(1B+1G+2Y)$$ $$=\frac{\binom{7}{2}\times \binom{4}{1}\times \binom{2}{1}}{\binom{13}{4}}+\frac{\binom{7}{1}\times \binom{4}{2}\times \binom{2}{1}}{\binom{13}{4}}+\frac{\binom{7}{1}\times \binom{4}{1}\times \binom{2}{2}}{\binom{13}{4}}$$ $$=\frac{56}{143}$$ Where $3C=$three colors, $B$=number of black ball,$G=$number of green ball,$Y$=number of yellow ball
Answer: You need to specify if you pick the three balls at the same time, or if you put them back before you pick the next one.
Edit : Sorry, the information was present but had been removed by the first reviewer... :-/


I need to have my site visitors post comments even if they are not logged in as a member

Question: I need to have my site visitors post comments even if they are not logged in as a member in my drupal 7 site. How do I do that? or is it better to have them sign up so they can post comments?
Comment: Check permission settings..
Answer: You need to give the "anonymous user" role permissions to post comments. Go to admin/people/permissions and look for the Comment section. Check the box for "Post comments" for the Anonymous user role, then save the settings.
I would not suggest this unless you have good anti-spam measures in place. You can search drupal.org for modules in the Spam Prevention category to help with that. Otherwise, I would require users to sign in before posting comments.
Note that even when requiring users to sign in to post comments, you'll still likely run into spam. Couldn't hurt to look into the list of modules linked to above.
Comment: great! looking into this anti-spam modules. thanks!
Answer: One possibility is to use the Disqus remotely hosted comments system. Users do need to log in to that - but not to your site. They can use a number of other sites they already have accounts in like Facebook or Google.


Silicon Laser and Laser mirrors

Question: If I will place Silicon as the active medium to create a Silicon Laser. Why I cannot achieve Lasing ? secondly, why do we always consider Laser mirrors in an standing position along the optical axis why we cannot use the active medium confined in a spherical ball shape mirror where we could place our active medium ?
Answer: a) Sillicon is an indirect semiconductor, hence, photon emission (stimulated or spontaneous) is extremely difficult to achieve or inefficient respecively (photon emission needs an electron AND phonon, simultaneously which is very unlikely). I think there was a demonstration of a silicon laser, but only with a lot of tricks and very inefficient.
b) ball shaped cavity should also be possible (with active medium inside). This is an interesting idea, probably it is not easy to realize - but I see no objections why it should not be possible. There might be issues with polarization, when the gain medium has different gain for different polarization (as it is common in semiconductor lasers). Some gain media only provide gain for one polarization. This might affect the operation in a ball shaped cavity.
But note that conventional laser cavity mirrors may also be spherical. Then the focal points are in the center of the cavity. So the whole configuration is essentially cut-out from a ball-type cavity, so ball type cavities must work.
Answer: Laser Mirrors are used for beam-steering in demanding laser applications. Laser Mirrors are Optical Mirrors that have been designed for specific laser types or wavelengths.Optics' Laser Mirrors feature dielectric coatings that have been optimized for high reflectance at specific laser wavelengths. Edmund Optics' dielectric coatings typically feature greater than 99% reflection at the design wavelength. Additionally, these coatings can withstand moderate to high laser powers.

Silicon Laser and Laser mirrors


Hangouts Face icons dim to bright

Question: Help me understand icons under messages going from live then back to dim under message.
When I send a message on hangouts the contact face shows live under the message, then reverts back to dim above the message.
Answer: So, you know how when you receive a message, there's a notification at the top of your screen? (When the icon is bright, it means person in question is looking at your message) Maybe it means that they have seen the notification, but have not yet responded and continued doing  what they had  been doing.

Hangouts Face icons dim to bright


How to calculate Calories in KCal from time and distance running

Question: I am working on a school project and I need a simple equation for calculating the number of Calories burnt when running from time(in milliseconds, could be seconds, minutes, and so on..) and distance(in meters, could be in kilometers, and so on..). Do I need a bodymass? if yes it can be included. Can somebody help me? I've spent 3 days of googling and didn't find a proper answer.
Comment: You might have more luck if you  were able to include heart-rate data.
Comment: Hi @Niall, one's heart rate has little to no bearing on their energy expenditure, as one's heart rate can vary depending on many factors. Greg Doucette elaborates on this point: https://m.youtube.com/watch?v=SLkCSkhgKp8
Answer: Here you go. You just need to have avarage HR and time
One of the more standard and most accurate ways to calculate the equation is to use the calorie expenditure formula below .  It comes from the Journal of Sports Sciences and provides a formula for each gender.
Men use the following formula:
Calories Burned = [(Age x 0.2017) — (Weight x 0.09036) + (Heart Rate x 0.6309) — 55.0969] x Time / 4.184.
Women use the following formula:
Calories Burned = [(Age x 0.074) — (Weight x 0.05741) + (Heart Rate x 0.4472) — 20.4022] x Time / 4.184.
ref: http://fitnowtraining.com/2012/01/formula-for-calories-burned/
or less accurate formula:
Running (total calories spent per mile)
.75 x your weight (in lbs.)
Running (Net calories spent per mile)
.63 x your weight
Adapted from "Energy Expenditure of Walking and Running," Medicine & Science in Sport & Exercise, Cameron et al, Dec. 2004.
ref:http://www.runnersworld.com/weight-loss/how-many-calories-are-you-really-burning
Answer: .First of all, there's no specific formula. Running involved various factors when it comes to calorie consumption. Like, at what speed you are running, what's your weight and what's the wind resistance also the slope . There are other details, but if we keep in mind the above, you can get a rough estimate. Remember, those treadmills that give the results of your calorie expense after running, just do an estimate, it's not accurate. Your calorie expenditure could be anywhere between +/- 20% of what the results show.
Having said that, you need to start from the amount of force your legs generate during impact on the ground. That multipled by distance you run, is the work done of calories burned. It's not that easy as the distance has to be liner. Physics says work = force X displacement, which means if you are running in a circle and end up at the same point, your displacement is 0 so work done is 0, correct? Doesn't make sense when you are so beat after running 20 rounds of the soccer ground.  So for the sake of your ease, just keep it limited to the distance you cover.
If you are running up the slope, your work done will be against gravity. Instead of distance, you need to consider the height you have reached above the point where  you started and multiply it with your weight. That's the potential energy gained by your body, or calories lost.
So, it will all give you a rough estimate, not anything absolute. Also, there are several factors like breathing, chemical reactions in your body that's not taken into account, because body burns calories when when you are at rest. So, I'd say it's complex and differes for every human. If you go by physics that I explained above, remember, that the margin of error would be around 20% or even higher.
Note: Dont fall for scams that claim they can get the exact count of your body's calorie expenses. Those products are just to make money, and to trap people with limited knowledge about how the stuffs work. Wish you the best.


Adjusting distance of blended objects to start and end points in Illustrator

Question: I am trying to create a row of houses along a curved patch using the blend tool.
What ruins the design though is the fact, that Illustrator is putting the first and second and last and second to last houses (highlighted by a red rectangle) closer to each other than the rest of the blended object are.
Why is that so and how do I change mentioned spacing to match the rest of the blended objects?
Answer: With your blend selected double-click blend icon in tool panels and select specified distance.


Will my trees recover from deer eating the leaves?

Question: Deer have eaten the leaves of my trees. I think they are holly. I am trying to protect them with deer repellant spray and eventually a fence. If I can keep the deer away, will my trees recover and fill back in? How can I help them recover?
Answer: The trees look fine..only the lower portion of the trees are eaten by them. This should not affect those trees...if not eaten again, I hope they will produce new leaves.
However, put up a fence upto the height where deer can reach, repellent spray can only help a bit,but not a solution.. I think.
Answer: Your trees may not be permanently damaged this year, but once deer find a plant they like, they continue to eat it. When I lived in a rural area, a joke we had was "Deer first eat your favorite plants, then when those are gone, they go for your most expensive plants. When those are gone, they eat any plants that have landscape value (like hiding a disagreeable view or enhancing an agreeable one), and then anything that's somewhat exotic. Finally, they'll get around to eating native plants. You'll know they're done with your property when you're looking out your windows and seeing only buckthorn, honeysuckle, and grass."
My experience living in "deer country" has led me to conclude that it's far easier to live with them than to try to prevent them from doing something that you don't like, such as eating your plants. In your case, that means limbing your trees up to about 6-7 feet or so from the ground and then installing hardware cloth cylinders around their trunks until they (the trunks) reach 8" caliper (diameter four feet from the ground) to deter the bucks from rubbing the trunks. This will actually benefit you, too, in that it will be easier to mow around/under the limbs. It won't hurt the trees, either.
As for perennials, we planted a TON of poisonous plants, which did indeed seem to deter the deer from eating them.
Comment: +1 limb to 6-7 feet -- try to find a way to live with them in peace if you can.
Answer: Fence around each tree. deer will eat most leaves they can reach. You need no action for those trees to recover.  However, the deer will nibble every year until all remaining leaves are out of reach. Those do not look like Holly from the photo. I have a lot of holly and a lot of deer; they cause minimum damage to holly. Most of my holly damage is to the bark from antler rubs. Years ago I tried any spray I could find with little success. Some helped for awhile until rain or dew washed it off.
Answer: I'd suspect that those lower branches are simply done.
I had a similar story some years ago, in an unusually snowy and cold winter here in Minnesota (U.S.), where the deer ate all the greenery off several large arbor vitae trees. Up to about 5 feet. They surely were desperate, because there was no other episodes in 30+ years where they ate the arbor vitae. (Some nice young white pine saplings, and aspen saplings, sure, any time!)
Before trimming the denuded branches, I waited a year or two, but nothing was happening, so I did trim off the apparently-dead branches.
In particular, if the deer ate those leaves in the summertime, you've got an intense, on-going problem. Fences. Looks like that's your specific situation. My sympathies. On another hand, if they did or do eat something only in an unusual winter, it's a one-off, and not worth the trouble to deal with.


Update a field value to random number

Question: I want to do a bulk update on any  when the filed  have a null value. Update the field to have random number. Kindly help me with code.
Comment: Have you looked at Math.random() function? Or maybe just Datetime in epoch format? What is the use case for updating a random number?
Comment: What have you tried? Where are you stuck? SFSE is happy to help with specific technical problems, but strongly discourages requests for others to write code for you. See [ask] and [help/on-topic].
Answer: I would like to suggest you use the Math.random() function to get random numbers.
Math.random() function returns a value :- A floating-point, pseudo-random number between 0 (inclusive) and 1 (exclusive).
Here in this example given below, I have used 100. This 100 is a limit of the range of random number like it will generate random values from 0 to 100(exclusive) because if I don't use any value as a limit like this
Integer randomNumber = Integer.valueOf(Math.random());

then it will generate a value between 0(inclusive) and 1(exclusive) and as I am getting values in Integer data-type, I will only get 0 as output(in the case when don't give any limit).
List<Account> accList = [SELECT Id, NumberOfEmployees FROM Account WHERE NumberOfEmployees = null LIMIT 1000];
for(Account acc: accList){
    Integer randomNumber = Integer.valueOf((Math.random()*100));
    acc.NumberOfEmployees = randomNumber;
}
update accList;
System.debug(accList);

Hope this explanation will resolve your query.
Thanks
Akshay

Update a field value to random number


DirectX Window Class

Question: After figuring out DXGI, I wrote a class that combines the act of creating a window and its associated swap chain (as well as an OOP approach to messages).  The class supports different window modes that are useful for games and editors, and handles XInput behind the scenes, combining gamepad, mouse, and keyboard controls into one domain.
I am primarily concerned with the design at this point - I have yet to take any classes at my school related to design, and a lot of my code winds up being a bit hacky.  If this is sensible (or at least passable for use in a game of my own), though, I would like to know.
#pragma once

#ifdef _MSC_VER
    #pragma comment(lib, "d3d11.lib")
    #pragma comment(lib, "dxgi.lib")
    #pragma comment(lib, "XINPUT9_1_0.lib")
    #pragma comment(lib, "DXWindow.lib")
#endif

#include <Windows.h>
#include <d3d11.h>
#include <dxgi.h>
#include <Xinput.h>
#include <comdef.h>
#include <atlbase.h>
#include <vector>
#include <string>

class DXWindowFactory;
class DXWindow;

class DXWindow final {
public:
    struct RESOLUTION {
        WORD Width;
        WORD Height;
    };

    enum WINDOW_MODE {
        WINDOW_MODE_WINDOWED = 0, //Non-resizable window with border
        WINDOW_MODE_BORDERLESS = 1, //Non-resizable window without border
        WINDOW_MODE_MAXIMIZED = 2 //Non-resizable maximized window without border
    };

    enum FULLSCREEN_MODE {
        FULLSCREEN_MODE_FULLSCREEN = 0, //Exclusive fullscreen (Native resolution)
        FULLSCREEN_MODE_FULLSCREEN_WINDOW = 1 //Non-exclusive fullscreen (Desktop resolution)
    };

    struct DESC {
        RESOLUTION Resolution; //Resolution of the window in windowed or borderless mode
        LPCWSTR Name;
        WINDOW_MODE WindowMode;
        FULLSCREEN_MODE FullscreenMode;
        BOOL InitFullscreen;
        BOOL AllowToggle;
    };

    struct MessageCallback {
        //Gamepad methods
        virtual void OnButtonDown(DWORD dwUserIndex, WORD wButton) { }

        virtual void OnButtonUp(DWORD dwUserIndex, WORD wButton) { }

        virtual void OnLeftAnalogMove(DWORD dwUserIndex, SHORT xPos, SHORT yPos) { }

        virtual void OnRightAnalogMove(DWORD dwUserIndex, SHORT xPos, SHORT yPos) { }

        virtual void OnLeftTriggerMove(DWORD dwUserIndex, BYTE Val) { }

        virtual void OnRightTriggerMove(DWORD dwUserIndex, BYTE Val) { }

        //Keyboard methods
        virtual void OnKeyDown(WPARAM Key, LPARAM lParam) { }

        virtual void OnKeyUp(WPARAM Key, LPARAM lParam) { }

        //Mouse methods
        virtual void OnLButtonDown(WORD Flags, WORD xPos, WORD yPos) { }

        virtual void OnLButtonUp(WORD Flags, WORD xPos, WORD yPos) { }

        virtual void OnRButtonDown(WORD Flags, WORD xPos, WORD yPos) { }

        virtual void OnRButtonUp(WORD Flags, WORD xPos, WORD yPos) { }

        virtual void OnMButtonDown(WORD Flags, WORD xPos, WORD yPos) { }

        virtual void OnMButtonUp(WORD Flags, WORD xPos, WORD yPos) { }

        virtual void OnMove(WORD Flags, WORD xPos, WORD yPos) { }

        virtual void OnWheel(WORD Flags, SHORT Delta, WORD xPos, WORD yPos) { }

        //Window methods
        virtual void OnClose() { }

        virtual void OnMinimize() { }

        virtual void OnMaximize() { }

        //Buffer methods
        virtual void OnBufferCreate() { }

        virtual void OnBufferRelease() { }
    };

    ~DXWindow();

    HRESULT PumpMessages();

    HRESULT Present(UINT SyncInterval, UINT Flags);

    void RegisterCallback(MessageCallback& Callback);

    void UnregisterCallback(MessageCallback& Callback);

    DXGI_FORMAT GetFormat();

    HRESULT GetBackBuffer(ID3D11Texture2D** ppBackBuffer);

    HRESULT GetBackBuffer(CComPtr<ID3D11Texture2D>& BackBuffer);

    HRESULT SetWindowMode(WINDOW_MODE Mode);

    WINDOW_MODE GetWindowMode();

    HRESULT JumpWindowMode(WINDOW_MODE Mode);

    HRESULT SetFullscreenMode(FULLSCREEN_MODE Mode);

    FULLSCREEN_MODE GetFullscreenMode();

    HRESULT JumpFullscreenMode(FULLSCREEN_MODE Mode);

    HRESULT SetFullscreen(BOOL Fullscreen);

    BOOL GetFullscreen();

    HRESULT SetWindowResolution(RESOLUTION Resolution);

    RESOLUTION GetWindowResolution();

    void SetAllowToggle(BOOL AllowToggle);

    BOOL GetAllowToggle();

private:
    DXWindowFactory& m_WindowFactory;

    CComPtr<IDXGISwapChain> m_SwapChain;
    CComPtr<ID3D11Device> m_Device;
    CComPtr<ID3D11DeviceContext> m_DeviceContext;

    HWND m_Handle;
    RESOLUTION m_Resolution;
    WINDOW_MODE m_WindowMode;
    FULLSCREEN_MODE m_FullscreenMode;
    BOOL m_InFocus;
    BOOL m_Fullscreen;
    BOOL m_AllowToggle;
    std::vector<MessageCallback*> m_Callbacks;
    XINPUT_STATE m_PrevGamepadState[4];
    DWORD m_WindowStyle;
    DWORD m_WindowExStyle;

    explicit DXWindow(DXWindowFactory& Factory);

    DXWindow() = delete;

    DXWindow(const DXWindow& Copy) = delete;

    HRESULT Initialize(const DESC& Desc);

    static LRESULT CALLBACK StaticWndProc(HWND handle, UINT message, WPARAM wParam, LPARAM lParam);

    LRESULT WndProc(UINT message, WPARAM wParam, LPARAM lParam);

    HRESULT RegisterWindowClass(DESC& desc);

    HRESULT MakeWindow(DESC& desc);

    HRESULT CreateSwapChain(CComPtr<IDXGIAdapter> adapter);

    HRESULT ResizeBuffers();

    HRESULT KillFocus();

    HRESULT SetFocus();

    HRESULT CenterWindow();

    HRESULT DefaultWindowPos();

    HRESULT CenterCursor();

    HRESULT CheckGamepads();

    HRESULT ToggleFullscreen();

    void WindowModeSetStyle();

    friend class DXWindowFactory;
};

Above is the window class.  Most of the methods are rather straightforward, and the only thing I feel the need to point out is how the window modes work.  There are 5 modes: Windowed, Borderless, Maximized, Fullscreen, and Fullscreen Window.  They are separated into two categories: Windowed, and Fullscreen modes.  This is because the window supports toggling between fullscreen and non-fullscreen with F11 (much in the way a browser does).  SetWindowMode and SetFullscreenMode both change the appearance of their respective modes and only immediately modify the window if their modes are in effect (IE, SetWindowMode will only instantly change the window if it's windowed, borderless, or maximized).  If they are not, the changes will be made on toggle.  JumpWindowMode and JumpFullscreenMode, however, immediately set the window to the given mode.
Given that mouthful, I'm debating whether or not the distinction is actually useful.
class DXWindowFactory final {
public:
    DXWindowFactory();

    ~DXWindowFactory();

    HRESULT Initialize(LPCWSTR LargeIcon = NULL, LPCWSTR SmallIcon = NULL, LPCWSTR Cursor = NULL);

    HRESULT CreateDXWindow(const DXWindow::DESC& Desc, DXWindow*& pWindow);

    void GetDevice(ID3D11Device** ppDevice);

    void GetDevice(CComPtr<ID3D11Device>& Device);

    void GetDeviceContext(ID3D11DeviceContext** ppDeviceContext);

    void GetDeviceContext(CComPtr<ID3D11DeviceContext>& DeviceContext);

private:
    CComPtr<ID3D11Device> m_Device;
    CComPtr<ID3D11DeviceContext> m_DeviceContext;
    CComPtr<IDXGIAdapter> m_Adapter;

    HRESULT CreateDevice();

    HRESULT RegisterWindowClass(LPCWSTR LargeIcon, LPCWSTR SmallIcon, LPCWSTR Cursor);

    void GetAdapter(CComPtr<IDXGIAdapter>& Adapter);

    friend class DXWindow;
};

This is the factory class that creates the window.  It is necessary in situations where multiple windows might be created, since it makes little sense to create a new Direct3D Device for every window, or query adapter outputs or what have you.  You probably notice the friend keyword.  That's something that I think is hacky, but ultimately I think it helps to boil down usage of the two classes to just a few lines.
I'd also love to know how well this works on other devices.  I've created a repository here with a MSVC 2013 project that should hopefully build without issues.  The test project basically just allows testing of window mode switching with the F1 - F7 keys.
EDIT: I also made a branch (post-cr) if you're looking for the current code.
Answer: Your code seems fine, though I'm only looking at the interface, not the implementation. Since you haven't got any architectural or DX related answers yet, I'll mention a few things I believe could be improve in this code.

A header file is no place for this:

#ifdef _MSC_VER
    #pragma comment(lib, "d3d11.lib")
    #pragma comment(lib, "dxgi.lib")
    #pragma comment(lib, "XINPUT9_1_0.lib")
    #pragma comment(lib, "DXWindow.lib")
#endif

That would be much better suited in a source (.cpp) file, since it is an implementation detail. The set of linked libraries is not relevant to the code including your header file, not to mention that this is a compiler specific feature that people not familiar with VS might not even know what it means, thus only causing distraction.
Your enums are already sequential and starting from zero. No need to explicitly supply the values. That's only maintenance overhead when other values must be added.
A very important thing: MessageCallback is an abstract base class, however, it is missing a virtual destructor! If anyone were to delete an instance of a derived class thru a MessageCallback pointer, it would invoke undefined behavior, due the lack of a virtual destructor. See When to use virtual destructors?
In DXWindowFactory, you have provided methods that operate on raw pointers and overloads that operate on smart pointers (CComPtr). My advice would be to disallow operations on raw pointers. Keep the smart pointer versions only, to avoid unsafe uses of your class.
I see a few instances of NULL here and there, but your code is clearly C++11, so why not use the much superior nullptr?
Comment: On the last point - Windows APIs tend to use NULL.  Any time I invoke a method or function from a Windows API I tend to use (what seems to be) their common practice, whereas if I was using a STL container I would use nullptr.  No real rhyme or reason, I just think it's more consistent to do it this way.
Comment: @NmdMystery, fair enough.

DirectX Window Class


How to set up the system so that applications had to ask to get permission to launch an internet browser?

Question: Many application have following behavior: If you click to some part of them they start your primary internet browser to show you something on their homepage. I want to change my windows settings (then I want do it in my second operating system Ubuntu) in that way so if any application tries to start an internet browser if I want it to be started (by some kind of pop up) and ask me if I want start it. (If this is not possible I would like to know a way to ban some application from starting a web browser at all.)
Answer: You could create a mini program (e.g. AutoIt or similar on Windows, Bash script on Ubuntu) and set it as the "default web browser". This program would then ask if you actually want to open your browser.
On Linux, protocol associations are desktop-environment-specific, if I remember correctly. On Windows, this entails setting the program as the default handler for the HTTP, HTTPS and possible FTP protocols.
Update: Example Bash script, untested(!)
#!/bin/bash
zenity --question --text="Are you sure you wish to proceed?" && firefox "$@"

This depends on zenity, a handy utility to show dialogs from the command line/scripts.
Comment: Could you show a script that will pass all the arguments right please? So there will not be blank page on browser if I really want to let program to open a browser after passing script. If you do it I will give you my bounty. To set it as a default browser I find this [link](http://askubuntu.com/questions/79305/how-do-i-change-my-default-browser)
Comment: Please see the updated post.


Video embed field doesn't honor the autoplay settings

Question: So I have an embedded video field inside of a paragraph and want it to autoplay.  I have set the settings for the field to have it autoplay, but when the iframe is rendered the url has autoplay=0.  Are there other settings I need to enable to get this to work?
Answer: Use the following code to change autoplay to 1 in your template or Javascript file. It works for me.
<code>jQuery('.video-embed-field-launch-modal').attr('data-video-embed-field-modal', function(i, oldSrc) {
  var isAutoPlay = oldSrc.match(/autoplay=([^&]*)/);
  if (isAutoPlay && isAutoPlay[1] == 0) {
    return oldSrc.replace('autoplay=0', 'autoplay=1');
  }
});
</code>
Answer: Some extra info to add ... Google has updated their policy around auto play on websites .. To get auto play to work you need to add &mute=1 to the query string so that the sound is muted when the page loads and the video starts
See the policy here:
https://developers.google.com/web/updates/2017/09/autoplay-policy-changes
Without that parameter .. Chrome won't auto play at all .. Currently auto play with sound on Firefox 63, Edge &  IE 11 without the above parameter. Chrome won't auto play without the mute setting. Opera 56 doesn't appear to auto play at all.


Modifying the linux scheduler

Question: I want to change specific parameters of the linux CFS scheduler like the virtual runtime of particular processes dynamically ( vruntime parameter in the sched_entity ). Is there any definite method to do this? I have already looked at commands like nice() and it won't serve the purpose.
Answer: As far as I know, we can't change the vruntime, since it is maintained per task basis. Instead can check the current task's vruntime and other values per CPU basis, by issuing the below command                                                                                "#cat /proc/sched_debug"

Modifying the linux scheduler


Accurately printed CIE diagram

Question: This is more just for curiosity rather than actually wanting to get one, but is there a place where I could buy a printed version of the CIE xy colour space diagram which accurately recreates all of the visible colours outside of the regular printing gamuts?
Answer: Its not actually possible to do. Because that paper you print on needs to have properties not avalialbe. The color on the edge are very pure and can not be mixed. I dont also see any way they could be reflected either. Also the xy diagram is not the full color space just a slice of it.
Comment: Ok, how about something more specific: A surface with reflectance properties such that if you shine D65 on it a CIE standard observer would get XYZ tristimulus values which could be projected onto a maxwell triangle to build a diagram in x and y. It would be insanely difficult but should it not be possible in theory?
Comment: @Chuck No, it would require each element in the poster to have different wavelength charactersitics, white of the paper would aslo have to be perfect. Its not pssible to do this atleast untill we can print stuff that behaves like butterfly wings. Printing simply does not work this way. Its not just insanely expensive it requires tech we do not have.
Answer: I think there is no point pursuing "objective accuracy" for colors, because individual perception of colors is different. The current standard is merely a statistical result for human eye perception.
That is to say, it is possible for someone else to perceive the colors you regard identical as different.
Comment: Yes that's a good point but I still think it might make a cool poster or something if you had the "standard observer" calibrated diagram.

Accurately printed CIE diagram


Why would two protons repel?

Question: I understand that two protons would repel due to them both being positively charged, however, wouldn't the strong force act on the two protons pulling them together? Would this mean that in this case the electromagnetic repulsive force is greater than the strong force? If so why? If not why would they repel?
Comment: The [strong force](http://en.wikipedia.org/wiki/Strong_interaction) has a very short reach.
Comment: Adding onto ACuriousMind's comment, think about nuclei. In the nucleus, the protons are sufficiently close together that the strong force attraction is stronger than the electromagnetic repulsion.
Comment: Both of the comments above miss the main point of the question, which is why, despite the strength of the nuclear force, is there not a proton-proton bound nucleus?
Answer: The electromagnetic repulsion between two protons is a long-range force, depending on $1/r^2$, where $r$ is the separation of the two protons.
The electromagnetic repulsion between two protons is not the reason that they do not stick together; if they are forced together (or can tunnel through the Coulomb barrier) then short-range strong nuclear forces are much stronger than the electromagnetic force over separations $<1.7\times10^{-15}\ m$, yet they are unable to make a bound state consisting of two protons.
The reason for this is that although the nuclear interaction is symmetric to the isospin of the nucleons (i.e. to first order it does not depend on whether the nucleons are protons or neutrons) it does depend on the spins of the two particles. The attractive nature of the force is only strong enough to bind the two nucleons if they have aligned spins (as in the bound state of the deuteron which has a neutron and proton with aligned spins and total angular momentum 1). If the two nucleons were identical however, i.e. a p+p or n+n interaction, then a bound state state with aligned spins would be forbidden by the Pauli exclusion principle.
The deeper reasons behind this spin dependence will need an answer from someone with a much better understanding of these issues.
Answer: Yea, a proton and neutron stick together, but two of the sam kind don't.  You don't get neutron balls even with only the interneucleon force and no electric repulsion.
I asked about it some years ago in a physics on-line forum, long before StackExchange. Ended up getting a textbook and eventually learning that "the force is largely insensitve to species (whether proton or neutron), but highly dependent on spin."
I got two different answers as to whether the diproton exists as a (fleeting) bound state.
The answer, relative to species and spin combinations of neucleons, has to do with "singlet state vs triplet state". That is a unique enough phrase that you ought to be able to search on that (e.g. class notes ...Hence the force is attractive for isospin singlets (T = 0) and repulsive for isospin triplets (T = 1).; more class notes in a nice PDF with illustrations.
Bottom line: the interneucleon force is not so simple as what you think of with gravity or electric or magnetic but with faster fall-off. It has complex behavior involving just how the particles are parked and what its neighbors are doing.
Comment: It is worth noting in this kind of context that the deuteron is stable by that Helium-2 is not. So one can not naive neglect the electromagnetic contribution to the energy.
Comment: Otoh, textbooks say that the electric force is completely irrelevant.
Comment: Well, two protons would stick together, but the Helium-2 that you got out would beta-decay to a deuteron pretty quickly.
Comment: Other sources state that a bound state never forms. From the class noted linked above (far easier than hittingnthe old dead-tree content!) *The implication is that two nucleons are not bound together if their spins are antiparallel and this is consistent with there being **no proton-proton** or neutron-neutron **bound states**. In the case of identical particles the bound parallel spin state is forbidden by the Pauli exclusion principle.*

Why would two protons repel?


Can Kensai Improve a Soulbow's weapon?

Question: I am preparing to DM a D&D 3.5e game. One of my players is trying to go Soulbow into Kensai. Can Kensai actually enhance the Soulbow's weapon? I am not sure if it can do that, as it is just an arrow that gets shot into enemies and dissipates.
Answer: Kensai and soulbow are both rather weak classes. The interaction is, officially, rather dubious (kensai has you choose a specific, individual weapon, not a kind of weapon, and each mind arrow is described as separate, freshly-manifested weapon, separate from any prior), but that isn't a good enough reason, in my opinion, to rule against this player. Their PC will most likely need all the help they can get.

Can Kensai Improve a Soulbow's weapon?


Phase transition and effect on leptogenesis

Question: What is the effect on leptogenesis in the standard model if the electroweak phase transition is (i) first order and (ii) second order?
Answer: In the Standard Model there is neither first nor second order electroweak phase transition (EWPT), but rather a crossover. To get a first order transition, additional particles are needed. There are many different theories (2HDM, Higgs portal, MSSM, ...) covering this topic.
Considering leptogenesis $\Delta L \neq 0$ we need a first order PT, since non-equilibrium is one of the Sakharov conditions required for leptogenesis. If these conditions are fulfilled, sphaleron processes violate lepton (or baryon) number by "jumping" from the symmetric $(\phi = 0)$ to the broken $(\phi=\phi_0)$ phase. I found this plot: (Never mind the numbers, in the case of EWPT the critical temperature $T_c \sim \mathcal{O}(100 GeV)$ )

Comment: This looks like a first order transition to me, or am I misreading the plot?


Check if user is 'voiced' or 'op' in IRC channel using twisted

Question: I'm writing an IRC bot using twisted python, and some actions should only be available to channel operators. How do I determine the 'user level' of a user in a channel using twisteds IRCClient?
Answer: One way to discover if a user has voice or op is to look at their name in a names listing.  See How to use Twisted to get an IRC channel's user list for details on how to do that.  Other solutions, using WHO or WHOIS, will take a similar form.
Answer: You can also use channel access lists if your bot has permissions to do so.


Missing Sybase ASE ODBC Driver in Windows 7

Question: I'm a ASP .Net developer and I have this application that queries from a Sybase 12 database in a database server.
Previously, I had Sybase 12 Open Client in my Win XP machine and I had the Sybase ASE ODBC Driver listed in the ODBC Admin screen.
My connection string is something like this: "Driver={SYBASE ASE ODBC Driver};Database=mydb;NA=something;uid=something..."
However, a few weeks ago, our machines were upgraded to Win7.
I found out that I have Sybsae 15 Open client in my machine now and I can't find the Sybase ASE ODBC Driver in the ODBC Admin screen, so it must not be installed.
When I asked the people here responsible for the Win7 upgrade, they said that the Sybase 12 driver is no longger compatible with Win7.
How am I supposed to continue working on the application I'm developing? Is there a Sybase ASE ODBC Driver for Win7 that I need installed? I just need something that will allow my code to connect to the same Sybase 12 database as it had been doing before.
Answer: That only comes with ASE.


iphone UitextView Text cut off

Question: I have a Uitextview that is populated with a text file.  I have a control on the page that allows the user to enable and disable paging.  I am having a problem where the top and/or bottom line of the text is sometimes "split in half" so you can only see the top or bottom half of the line.  I believe the code below should fix it.  The code gets the line height of the text and the frame height, figures out the number of lines that are visible on the screen, and creates a new frame height so it will fit. While the frame does get resized, it still "cuts off" the top and/or bottom line.  Anyone one have any suggestions?  Is my math wrong?
Thanks!!!
<code> - (void)fitText
    {

            CGFloat maximumLabelHeight = 338;
            CGFloat minimumLabelHeight = 280;

            CGSize lineSize = [theUiTextView.text sizeWithFont:theUiTextView.font];
            CGFloat lineSizeHeight = lineSize.height;
            CGFloat theNumberOfLinesThatShow = theUiTextView.frame.size.height/lineSize.height;

            //adjust the label the the new height
            theNumberOfLinesThatShow = round(theNumberOfLinesThatShow);

            CGFloat theNewHeight = lineSizeHeight * theNumberOfLinesThatShow;

            if (theNewHeight > maximumLabelHeight)
        {
            theNumberOfLinesThatShow = theNumberOfLinesThatShow - 1;
            theNewHeight = lineSizeHeight * theNumberOfLinesThatShow;
        }
        if (theNewHeight < minimumLabelHeight)
        {
            theNumberOfLinesThatShow = theNumberOfLinesThatShow + 1;
            theNewHeight = lineSizeHeight * theNumberOfLinesThatShow;
        }

            //adjust the label the the new height.
            CGRect newFrame = theUiTextView.frame;
            newFrame.size.height = theNewHeight;
            theUiTextView.frame = newFrame;
}
</code>
Answer: UIScrollView (and UITextView is a UIScrollView) seems to use a fixed 8-pixel inset on both sides. This seems to be independent of alignment or font size.
So, I think what you're missing here is the fudge factor of 16.0 - see this question.

iphone UitextView Text cut off


Is it possible to integrate Magento Go with a custom made system?

Question: Client would like to switch to Magento, specifically to Magento Go from currently used custom made webshop solution. Would it be possible to integrate Magento Go with this "in-house" system to use some of it's features - apart from writing the module and uploading to Magento Connect so that it may be installed from there?
Comment: Better naming of the product would be nice. When it comes to customization, you're dealing with "Magento STOP". If it cant' be done through the admin panels provided, it can't be done. For this kind of customization, you will be wanting Magento CE.
Answer: It's not possible to upload custom modules to be used in Magento Go stores. There are a limited number of Go extensions: http://www.magentocommerce.com/magento-connect/catalogsearch/result/?q=&pl=3&te=1
Without more knowledge of the type of integration you're hoping to implement you'll probably have a hard time or find it impossible to do so.
Answer: No it would not.  No tools or packages exist to do this, and the amount of custom programming needed would be tremendous.  Additionally, the only interaction Go allowed is via its API — you can't create MagentoGo extensions.
Finally, I used "allowed" above because Magento Go's been discontinued. Ebay will be shutting it down later this year.


How to make an internal load balancer in a google cloud kubernetes instance be accessible from another kubernetes instance in different regions?

Question: I am trying to expose a service inside of a Kubernetes cluster in one Google Cloud Region (us-east) and have it accessible to another Kubernetes cluster in a different region (us-central). I would highly prefer this traffic not use any public IPs but instead, stay on the internal to the project.
What I tried to setup was an Internal Google Cloud Load balancer. I didn't read till later that:

Internal load balancers are only accessible from within the same network and region.

I thought that was kind of odd and tried to work around it by applying firewalls or routes, but nothing seems to work. Anything inside of the region's subnet can reach the LB, but anything outside of that region can't.
Now, what is truly perplexing, I have this working in a different way on a different project. Here I have 2 projects that have peering setup, and this works just fine. However, this may be because they are both in the same region...
So my question: How do I connect two Kubernetes clusters and keep traffic internal to the google cloud without using public IPs but instead use the internal 10.x IPs. Reason for being so strict on the network traffic being internal is that I have isolated on one Kubernetes cluster and would rather not have that cluster have any public facing resource of any kind.
Answer: You may use a GKE Private Cluster. This is a Cluster not accessible to the public. This is a cluster that can only be accessed internally. Your cluster can only be exposed to the trusted VPC network. IP addresses are internal ones of the format 10.x.x.x.
Instructions on how to setup a Private Cluster can be found in this article.
Answer: Unfortunately ILBs are regional for now.


Do we need PSAD if we already have Fail2Ban?

Question: I already have installed Fail2Ban on my server. I planned to install PSAD on it. Are they equal? Isn't it a good idea to keep them both?
Answer: Fail2BAN scans log files of various applications such as apache, ssh or ftp and automatically bans IPs that show the malicious signs such as automated login attempts. PSAD on the other hand scans iptables and ip6tables log messages (typically /var/log/messages) to detect and optionally block scans and other types of suspect traffic such as DDoS or OS fingerprinting attempts. It's ok to use both programs at the same time because they operate on different level.
Comment: Is it okay if I quote you in a how-to guide I created? I am adding a section for PSAD and want to mention why we should use both PSAD and Fail2Ban. I can't summarize it any better than you did so I figured I would just quote you. https://github.com/imthenachoman/How-To-Secure-A-Linux-Server/


Boiled Ribs left in water overnight, parents say its fine to eat

Question: So my dad boiled ribs this morning, and it was left on the counter for like 14 hours and I said its probably not safe to eat cause they say after 2 hours you shouldn't eat it, but they said cause it was in water and  not exposed outside of the water its still good and I find that to be hard to believe.
Comment: Hi Kimbur, we closed this as a duplicate because, despite there being strict safety rules by the FDA, every day there are people who are trying to interpret them anew. If something is not mentioned in the answer to the older question, then it does not make any difference. Not being under water, nor anything else.
Answer: Well, your parents are largely right and also quite wrong on two different things.
Boiling is fairly effective at killing most of the bacteria and all the viruses that can cause "food poisoning", but will not denature some of the toxins produced by some bacteria that can cause illness after consuming. Clostridium species spores are not inactivated by boiling, but are not waterborne and only found in anaerobic conditions such as in the gut of animals. If your dad had spilled gut contents over the the meat before cooking, I would be a little worried, otherwise, not so much.
Assuming that the meat and other ingredients were not contaminated with these bacteria to a significant level before cooking, boiled stocks should be fine on the counter for a overnight after cooking if they are left undisturbed and covered. Depending on the volume in which they were boiled and the ambient temperature, I would be surprised if the boiled meats were below 60 C (generally considered the temperature at which waterborne enteric pathogens are killed) after 2 hours, and as such would be too hot to place in the fridge.
However, they are wrong about the air exposure bit - if the meat/water was exposed (i.e. not in a covered container) to the air overnight, there is a good chance that there will now be some bacteria and yeasts happily growing in the stock produced by boiling meat. Most of these bacteria will not cause illness, but many can cause "food poisoning" and should be treated with caution.


macOS Sierra - how to enable "Allow Remote Automation" using command line

Question: I am working on an automation stuff in macOS Sierra (10.12.2). By using python's atomac support I can launch the safari browser and make the settings enabled via Safari ->  Preferences -> Advanced -> check "enable Develop Menu" and then select "Develop -> Allow Remote Automation". Looks like this is not so consistent for automation perspective. I would like to know if there is any shell command to make this possible.
Comment: Ok, short on time, but you could do `defaults write com.apple.Safari IncludeDevelopMenu YES` to activate the development menu via terminal. I could not easily locate the .plist file that houses the 'Allow Remote Automation' option, but there should be one and you should be able to use the defaults command on that as well. Or you could use Apple's osascript and simulate the mouse-clicks (would not recommend that). Using Python, I'd try using subprocess.Popen() on the defaults command. Will try later tonight unless your question is already answered by then.
Comment: anyone looking to see a working applescript solution to what's described in the above comment should check out: https://stackoverflow.com/a/47387407/332922
Comment: Hi @RianSanderson, probably you could add this is an answer. So that, I could recognize your contribution. Cheers!
Answer: Hmm ok, so as per my comment:
You could do defaults write com.apple.Safari IncludeDevelopMenu YES to activate the development menu via terminal. You could get python to execute this command for you using the subprocess module.
According to this this question it seems that one used to be able to simply do defaults write com.apple.Safari AllowRemoteAutomation 1. However, since Safari 10 this option has apparently been subjected to a higher security protocol or something (maybe because of the System Integrity Protection that was introduced). I've been looking for the plistfile that now holds the setting, but I have not been able to find it. Maybe it's not even there in an actual plistfile anymore.
I guess this leaves you with 2 options:

Use apple's osascript to simulate the needed mouseclicks.
Repost your question on AskDifferent or Apple's own developers forum, since you are more likely to find someone with in-depth knowledge of macOS.
Comment: Thanks for the answer but it didn't work. Will go with the suggested  forums in leisure time. Thanks again!
Answer: I found the answer from: https://developer.apple.com/documentation/webkit/testing_with_webdriver_in_safari
safaridriver --enable

It will prompt for an admin password, so some people setup passwordless sudo (dangerous) or do another workaround like calling from an Applescript
I tested that this works with Mojave and Safari 12.0.3 and verified that it works regardless of if the Develop menu is enabled, though you probably want to save yourself the clicks and just enable that too:
defaults write com.apple.Safari IncludeDevelopMenu 1

Answer: On MacBook Pro (Apple M2 Pro)
▪   select Safari
▪   Select Setting
▪   Select "Advanced" tab
▪   Check "Show features for web developers"
▪   Now you see "develop" option is on the MacOS menu
⁃   select develop
⁃   Select "Developer settings…"
⁃   check  "Allow remote automation"
Now you can run your tests against safari


What is the point of a bitcoin faucet?

Question: What is the motivation for the faucet owner?
Just to get a browser visit/IP address/plant some cookies?
Answer: George gave you the idealistic answer.  The cynical answer: the point is to get you to look at ads and produce revenue for the faucet operator, while paying you an amount of Bitcoin that you hopefully won't realize is equivalent to an hourly wage several orders of magnitude below sweatshop.
Answer: Most of them use Bitcoin Based Advert Company's to monetize them and don't pay out much money so they generate a profit and run multiple faucets.
Bitcoin Based Advert Company's
Also they make use of things like referral codes to other faucets which can quickly get them back the amount of Satoshi they pay out as most people keep browsing through lots of faucets.
There are other things like paid url shorteners used to generate revenue.
Answer: The intention behind the first faucets, e.g. the original one by Gavin Andresen, was to promote the use of Bitcoin by putting a few easily in the hands of whomever willing to use them. Back in e.g. 2010, 5 bitcoins was a very insignificant amount, but that way anybody could try the system. A similar initiative was called "Pay It Forward" where you would get a few bitcoins and send them to other people. The latter was implemented as a forum thread where the original poster edited the first post to add your address if you wanted to participate.
Obviously, now that many people see economical value in Bitcoin before technical value, such systems would not stand for a minute. The concept and name of Bitcoin faucets still exist, but that's pretty much all they share with the first faucets. The modern ones are a way to make money rather than a way to stimulate the use of Bitcoin by the community.

What is the point of a bitcoin faucet?


add item to next column in wrapgrid

Question: I have a GridView like this
<GridView x:Name="TestGridView"  SelectionMode="None">
  <GridView.ItemsPanel>
    <ItemsPanelTemplate>
      <WrapGrid Orientation="Vertical" ItemWidth="300" ItemHeight="80"  Height="480" VerticalAlignment="Top"  />
    </ItemsPanelTemplate>
  </GridView.ItemsPanel>
</GridView>

One of my GridViewItem contains a button, when I click this Button, a new GridViewItem will added to the GridView dynamically, I want the maximum number of GridViewItem is 8, after the eighth GridViewItem added to the GridView, the Button collapsed. Then add some other GridViewItem in next column of the GridView, but the 8th GridViewItem doesn't occupy all the space of the 2nd column, if I add new GridViewItem, it will automatically added to the 2nd column below the 8th GridViewItem. How to explicitly add GridViewItem to the next column?
Answer: I think you can use group, there is a group collection in gridview. you can just add 8 item in a group, and then set other in the new group.

add item to next column in wrapgrid