text:
Q: how can I write netflix zuul filter to change response location header attribute? I have downstream service that redirect to x.jsp this location is not in gateway route for example
gateway route --- localhost:8080/app - 192.168.1.1:80 (DownStream app)

in DownStream app when a user is not logged in, it redirects to 192.168.1.1:80/Login.jsp, which is in the Location header of the response.
This URL is not using the gateway.
I want to write a zuul filter to change this redirect url by mapping in zuul routes dynamic for example for each url that routes in zuul filter change Location header by the gateway. How can I do that?

A: You downstream app should respect the x-forwarded-* headers, and not generate redirects like that. But the following filter will change the redirect location for you anyway:
@Override
public String filterType() {
    return "post";
}

@Override
public int filterOrder() {
    return 0;
}

@Override
public boolean shouldFilter() {
    int status = RequestContext.getCurrentContext().getResponseStatusCode();
    return status >= 300 && status < 400;
}

@Override
public Object run() {
    RequestContext ctx = RequestContext.getCurrentContext();
    Map<String, String> requestHeaders = ctx.getZuulRequestHeaders();
    Optional<Pair<String, String>> locationHeader = ctx.getZuulResponseHeaders()
                .stream()
                .filter(stringStringPair -> LOCATION.equals(stringStringPair.first()))
                .findFirst();

        if (locationHeader.isPresent()) {
            String oldLocation = locationHeader.get().second();
            String newLocation = ...
            locationHeader.get().setSecond(newLocation);
        }
    return null;
}


text:
Q: How do I get the line text from a JEditorPane for the line where my cursor is currently positioned? I have a JEditorPane and I put a mouse listener on it and can detect where the cursor is.
However, I would like to be able to get the text of the line where my cursor is. Is there a utility method I can use? If not, then how would I construct a method to do this?
        xmlEditor.addMouseListener(
            new MouseAdapter() {
                public void mouseClicked(MouseEvent me) {
                    try {
                        int caretPosition = xmlEditor.getCaretPosition();
                        int offset = 0;
                        int length = 0;
                        xmlEditor.getText(offset, length);
                    } catch (BadLocationException ex) {
                        Logger.getLogger(EZXPathFrame.class.getName()).log(Level.SEVERE, null, ex);
                    }
                }
            }
        );

A:
Is there a utility method I can use?

Never tried it with a JEditorPane but you might be able to use the Utilities class. You should be able to use methods like getRowStart(...) and getRowEnd(...). Once you know the starting and ending offset you can get the text from the JEditorPane.
Something like:
int start = Utilities.getRowStart(textComponent, offset);
int end = Utilities.getRowEnd(textComponent, offset);
String text = textComponent.getText(start, end-start);

redpajama_set_name: RedPajamaStackExchange


text:
Q: I am getting below error while compiling spark program in SBT Versions used:
Spark version: 2.3.2
Scala version: 2.11.8
SBT version: 1.2.4
build.sbt:
name := "spark_demo"

version := "0.1"

scalaVersion := "2.11.8"

libraryDependencies ++= Seq(
  "org.apache.spark" %% "spark-core" % "2.3.2",
  "org.apache.spark" %% "spark-sql"  % "2.3.2",
  "org.apache.spark" %% "spark-hive"  % "2.3.2"
)

Error:


text:
Q: Principal component analysis on proportional data Is it valid to run a PCA on data that is comprised of proportions? For example, I have data on the proportion of various food items in the diet of different species. Can I run a PCA on this type of data or should I transform the data or do something else beforehand?

A: I had a similar question. You should search for "compositional data analysis". There are transformation to apply to proportions in order to analyze them with multivariate tecniques such as PCA. You can find also "robust" PCA algorithms to run your analysis in R. Let us know if you find an appropriate solution to your specific problem.

A: I don't think so.
PCA will give you "impossible" answers. You might get principal components with values that proportions can't have, like negative values or values greater than 1. How would you interpret this component?
In technical terms, the support of your data is a subset of the support of PCA. Say you have $k$ classes. Then:

*

*the support for PCA vectors is $\R^k$

*the support for your proportion vectors is the $k$- dimensional simplex. By simplex I mean the set of $p$ vectors of length $k$ such that:

*

*$0 \le p_i \le 1$ where $i = 1, ..., k$

*$\sum_{i=1}^k{p_i} = 1$

One way around this is if there's a one to one mapping between the $k$-simplex to all of $\R^k$. If so, you could map from your proportions to $\R^k$, do PCA there, then map the PCA vectors to the simplex.
But I'm not sure the simplex is a self-contained linear space. If you add two elements of the simplex, you don't get an element of the simplex :/
A better approach, I think, is clustering, eg with Gaussian mixtures, or spectral clustering. This is related to PCA. But a nice property of clustering is you can express any element of your data as a "convex combination" of the clusters. If you analyze your proportion data and find clusters, they (unlike PCA vectors) will be within the simplex space, and any mixture of them will be, too.
I also recommend looking into nonnegative matrix factorization. This is like PCA but, as the name suggests, avoids negative components and also negative eigenvectors. It's very useful for inferring structure in strictly positive data, like proportions. But nmf does not give you a basis for simplex space.


text:
Q: Taking the derivative of definite integral? I'm having trouble understanding the derivative of definite integral. For example, why is the following true?
$\frac{d}{dx}\displaystyle\int_{0}^{x}F_{1}(x-v)f_{1}(v)\, \mathrm{d}v = \displaystyle\int_{0}^{x}f_{1}(x-v)f_{1}(v)\, \mathrm{d}v $
I mean I know that $\frac{d}{dx}F_{1}(x) = f_{1}(x)$ by the fundamental theorem of calculus, but the example I gave confuses me...what if the integration limit $x$ is a constant? Doesn't the derivative then equal $0$?
Could someone give me intuitive explanation? I understand it somehow, but I don't really get the intuition, perhaps the limits of integration or the notation confuses me...
here is a link to my original question, where I was asking about the $\chi^2$-distribution:
Help with understanding the $\chi^2$-distribution
I'd be thankful if someone could maybe write it out step by step so I could see what's going on :)

A: To illustrate (slightly heurustucally), you may contemplate what happens as $x$ is replaced with $x+h$ for small $h$.
We want to compute
$$\frac{\displaystyle\int_0^{x+h}F(x+h-v)f(v)\, \mathrm dv-\int_0^{x}F(x-v)f(v)\, \mathrm dv}h\\
=\frac1h\left(\int_0^{x}(F(x+h-v)f(v)-F(x-v)f(v))\, \mathrm dv +\int_x^{x+h}F(x+h-v)f(v)\, \mathrm dv\right)$$
Using $F(x+h-v)-F(x-v)=h\cdot f(x-v+\theta(x)h)$ for some $\theta(x)\in(0,1)$, and also that $F(x+h-v)f(v)$ is nearly constant on the tiny interval $[x,x+h]$, this is
$$
\approx\frac1h\left(\int_0^{x}h\cdot f(x-v+\theta(x)h)f(v)\, \mathrm dv +h\cdot F(0)f(x)\right)\\
=\int_0^{x} f(x-v+\theta(x)h)f(v)\, \mathrm dv
\approx\int_0^{x} f(x-v)f(v)\, \mathrm dv
$$
So we see (but should justify a bit more rigorously) that part of the result comes from differentiating the integrand, and part comes from the integrand at the upper limit (because the upper limit varies with $x$). In general, another contribution by the lower limit would be needed, but here that limit is constantly $0$, hence no change occurs:
$$ \frac{\mathrm d}{\mathrm dx}\int_{f(x)}^{g(x)}h(x,t)\,\mathrm dt=g'(x)h(x,g(x))-f'(x)h(x,f(x))+\int_{f(x)}^{g(x)}\frac{\partial}{\partial x}h(x,t)\,\mathrm dt.$$
The special thing that happens in your original problem is that the contribution by the upper limit is always $0$ because the factor $F(0)=\int_0^0f(x)\mathrm dx$ occurs.


text:
Q: Get center of any UIView in Swift I'm trying to write a global function that adds an activityIndicator to any view (mostly imageViews though) by calling such function.
The function I have right now is made of:
public func addActivityIndicatorToView(activityIndicator: UIActivityIndicatorView, view: UIView){

    //activityIndicator configuration ...
    activityIndicator.center = view.center
    view.addSubview(activityIndicator)
    activityIndicator.startAnimating()
}

But I don't get the center of the view for some reason.
I've also tried various solutions around SO and Google, but none worked until now.
Is there any way to get the center point and set the activityIndicator to any UIView?

A: The center property is relative to a view's superview. So if your view's frame is {10, 10, 20, 20}, center is going to be {20, 20}.
I'm guessing you want to center the activityIndicator in view.
You can do
activityIndicator.center = CGPointMake(view.width/2, view.height/2)

A: Original Answer:
I had reproduce your problem easily (see my comment).
I think it could be a problem of auto layout. So may be you can use constraints instead calculate position ?
func addActivityIndicatorToView(activityIndicator: UIActivityIndicatorView, view: UIView){

    self.view.addSubview(activityIndicator)

    //Don't forget this line
    activityIndicator.setTranslatesAutoresizingMaskIntoConstraints(false)
    view.addConstraint(NSLayoutConstraint(item: activityIndicator, attribute: NSLayoutAttribute.CenterX, relatedBy: NSLayoutRelation.Equal, toItem: view, attribute: NSLayoutAttribute.CenterX, multiplier: 1, constant: 0))
    view.addConstraint(NSLayoutConstraint(item: activityIndicator, attribute: NSLayoutAttribute.CenterY, relatedBy: NSLayoutRelation.Equal, toItem: view, attribute: NSLayoutAttribute.CenterY, multiplier: 1, constant: 0))

    activityIndicator.startAnimating()

}

Updated Code for Swift 5.0:

*

*From edit by Rob

*NSLayoutAttribute.CenterX is now NSLayoutConstraint.Attribute.centerX

*NSLayoutRelation.Equal is now NSLayoutConstraint.Relation.equal

*NSLayoutAttribute.CenterY is now NSLayoutConstraint.Attribute.centerY
func addActivityIndicatorToView(activityIndicator: UIActivityIndicatorView, view: UIView){

    self.view.addSubview(activityIndicator)

    //Don't forget this line
    activityIndicatorView.translatesAutoresizingMaskIntoConstraints = false
    view.addConstraint(NSLayoutConstraint(item: activityIndicator, attribute: NSLayoutConstraint.Attribute.centerX, relatedBy: NSLayoutConstraint.Relation.equal, toItem: view, attribute: NSLayoutConstraint.Attribute.centerX, multiplier: 1, constant: 0))
    view.addConstraint(NSLayoutConstraint(item: activityIndicator, attribute: NSLayoutConstraint.Attribute.centerY, relatedBy: NSLayoutConstraint.Relation.equal, toItem: view, attribute: NSLayoutConstraint.Attribute.centerY, multiplier: 1, constant: 0))

    activityIndicator.startAnimating()

}

A: Swift 3:
activityIndicator.center = CGPoint(x: view.width/2, y: view.height/2)

or you can try:
activityIndicator.center = view.center


text:
Q: What is the correct way to perform constant-space nested loops in Haskell? There are two obvious, "idiomatic" ways to perform nested loops in Haskell: using the list monad or using forM_ to replace traditional fors. I've set a benchmark to determine if those are compiled to tight loops:
import Control.Monad.Loop
import Control.Monad.Primitive
import Control.Monad
import Control.Monad.IO.Class
import qualified Data.Vector.Unboxed.Mutable as MV
import qualified Data.Vector.Unboxed as V

times = 100000
side  = 100

-- Using `forM_` to replace traditional fors
test_a mvec =
    forM_ [0..times-1] $ \ n -> do
        forM_ [0..side-1] $ \ y -> do
            forM_ [0..side-1] $ \ x -> do
                MV.write mvec (y*side+x) 1

-- Using the list monad to replace traditional forms
test_b mvec = sequence_ $ do
    n <- [0..times-1]
    y <- [0..side-1]
    x <- [0..side-1]
    return $ MV.write mvec (y*side+x) 1

main = do
    let vec = V.generate (side*side) (const 0)
    mvec <- V.unsafeThaw vec :: IO (MV.MVector (PrimState IO) Int)
    -- test_a mvec
    -- test_b mvec
    vec' <- V.unsafeFreeze mvec :: IO (V.Vector Int)
    print $ V.sum vec'

This test creates a 100x100 vector, writes 1 to each index using nested loop and repeats that 100k times. Compiling those with just ghc -O2 test.hs -o test (ghc version 7.8.4), the results are: 3.853s for the forM_ version and 10.460s for the list monad. In order to provide a reference, I also programmed this test in JavaScript:
var side  = 100;
var times = 100000;
var vec   = [];

for (var i=0; i<side*side; ++i)
    vec.push(0);

for (var n=0; n<times; ++n)
    for (var y=0; y<side; ++y)
        for (var x=0; x<side; ++x)
            vec[x+y*side] = 1;

var s = 0;
for (var i=0; i<side*side; ++i)
    s += vec[i];

console.log(s);

This equivalent JavaScript program takes 1s to complete, beating Haskell's unboxed vectors, which is unusual, suggesting that Haskell is not running the loop in constant space, but doing allocations instead. I've then found a library that claims to provide type-guaranteed tight loops Control.Monad.Loop:
-- Using `for` from Control.Monad.Loop
test_c mvec = exec_ $ do
    n <- for 0 (< times) (+ 1)
    x <- for 0 (< side) (+ 1)
    y <- for 0 (< side) (+ 1)
    liftIO (MV.write mvec (y*side+x) 1)

Which runs in 1s. That library isn't very used and far from idiomatic, though, so, what is the idiomatic way to get fast constant-space bidimensional computations? (Note this isn't a case for REPA as I want to perform arbitrary IO actions on the grid.)

A: In my experience forM_ [0..n-1] can perform well, but unfortunately it's not reliable. Just adding an INLINE pragma to test_a and using -O2 makes it run much faster (4s to 1s for me), but manually inlining it (copy paste) slows it down again.
A more reliable function is is for from statistics which is implemented as
-- | Simple for loop.  Counts from /start/ to /end/-1.
for :: Monad m => Int -> Int -> (Int -> m ()) -> m ()
for n0 !n f = loop n0
  where
    loop i | i == n    = return ()
           | otherwise = f i >> loop (i+1)
{-# INLINE for #-}

Using it looks similar to forM_ with lists:
test_d :: MV.IOVector Int -> IO ()
test_d mv =
  for 0 times $ \_ ->
    for 0 side $ \i ->
      for 0 side $ \j ->
        MV.unsafeWrite mv (i*side + j) 1

but performs reliably well (0.85s for me) without any risk of allocating a list.

A: Writing tight mutating code with GHC can be tricky sometimes. I'm going to write about a couple of different things, probably in a manner that is more rambling and tl;dr than I would prefer.
For starters, we should use GHC 7.10 in any case, since otherwise the forM_ and list monad solutions never fuse.
Also, I replaced MV.write with MV.unsafeWrite, partly because it's faster, but more importantly it reduces some of the clutter in the resultant Core. From now on runtime statistics refer to code with unsafeWrite.
The dreaded let floating
Even with GHC 7.10, we should first notice all those [0..times-1] and [0..side-1] expressions, because they will ruin performance every time if we don't take necessary steps. The issue is that they are constant ranges, and -ffull-laziness (which is enabled by default on -O) floats them out to top level. This prevents list fusion, and iterating over an Int# range is cheaper than iterating over a list of boxed Int-s anyway, so it's a really bad optimization.
Let's see some runtimes in seconds for the unchanged (aside from using unsafeWrite) code. ghc -O2 -fllvm is used, and I use +RTS -s for timing.
test_a: 1.6
test_b: 6.2
test_c: 0.6

For GHC Core viewing I used ghc -O2 -ddump-simpl -dsuppress-all -dno-suppress-type-signatures.
In the case of test_a, the [0..99] ranges are lifted out:
main4 :: [Int]
main4 = eftInt 0 99 -- means "enumFromTo" for Int.

although the outermost [0..9999] loop is fused into a tail-recursive helper:
letrec {
          a3_s7xL :: Int# -> State# RealWorld -> (# State# RealWorld, () #)
          a3_s7xL =
            \ (x_X5zl :: Int#) (s1_X4QY :: State# RealWorld) ->
              case a2_s7xF 0 s1_X4QY of _ { (# ipv2_a4NA, ipv3_a4NB #) ->
              case x_X5zl of wild_X1S {
                __DEFAULT -> a3_s7xL (+# wild_X1S 1) ipv2_a4NA;
                99999 -> (# ipv2_a4NA, () #)
              }
              }; }

In the case of test_b, again only the [0..99] are lifted. However, test_b is much slower, because it has to build and sequence actual [IO ()] lists. At least GHC is sensible enough to only build a single [IO ()] for the two inner loops, and then perform sequencing it 10000 times.
 let {
          lvl7_s4M5 :: [IO ()]
          lvl7_s4M5 = -- omitted
        letrec {
          a2_s7Av :: Int# -> State# RealWorld -> (# State# RealWorld, () #)
          a2_s7Av =
            \ (x_a5xi :: Int#) (eta_B1 :: State# RealWorld) ->
              letrec {
                a3_s7Au
                  :: [IO ()] -> State# RealWorld -> (# State# RealWorld, () #)
                a3_s7Au =
                  \ (ds_a4Nu :: [IO ()]) (eta1_X1c :: State# RealWorld) ->
                    case ds_a4Nu of _ {
                      [] ->
                        case x_a5xi of wild1_X1y {
                          __DEFAULT -> a2_s7Av (+# wild1_X1y 1) eta1_X1c;
                          99999 -> (# eta1_X1c, () #)
                        };
                      : y_a4Nz ys_a4NA ->
                        case (y_a4Nz `cast` ...) eta1_X1c
                        of _ { (# ipv2_a4Nf, ipv3_a4Ng #) ->
                        a3_s7Au ys_a4NA ipv2_a4Nf
                        }
                    }; } in
              a3_s7Au lvl7_s4M5 eta_B1; } in
-- omitted

How can we remedy this? We could nuke the problem with {-# OPTIONS_GHC -fno-full-laziness #-}. This indeed helps a lot in our case:
test_a: 0.5
test_b: 0.48
test_c: 0.5

Alternatively, we could fiddle around with INLINE pragmas. Apparently inlining functions after the let floating is done preserves good performance. I found that GHC inlines our test functions even without a pragma, but an explicit pragma causes it to inline only after let floating. For example, this results in good performance without -fno-full-laziness:
test_a mvec =
    forM_ [0..times-1] $ \ n ->
        forM_ [0..side-1] $ \ y ->
            forM_ [0..side-1] $ \ x ->
                MV.unsafeWrite mvec (y*side+x) 1
{-# INLINE test_a #-}

But inlining too early results in poor performance:
test_a mvec =
    forM_ [0..times-1] $ \ n ->
        forM_ [0..side-1] $ \ y ->
            forM_ [0..side-1] $ \ x ->
                MV.unsafeWrite mvec (y*side+x) 1
{-# INLINE [~2] test_a #-} -- "inline before the first phase please"

The problem with this INLINE solution is that it's rather fragile in the face of GHC's floating onslaught. For example, manual inlining does not preserve performance. The following code is slow because similarly to INLINE [~2] it gives GHC a chance to float out:
main = do
    let vec = V.generate (side*side) (const 0)
    mvec <- V.unsafeThaw vec :: IO (MV.MVector (PrimState IO) Int)
    forM_ [0..times-1] $ \ n ->
        forM_ [0..side-1] $ \ y ->
            forM_ [0..side-1] $ \ x ->
                MV.unsafeWrite mvec (y*side+x) 1

So what should we do?
First, I think using -fno-full-laziness is a perfectly viable and even preferable option for those who'd like to write high performance code and have a good idea what they are doing. For example, it's used in unordered-containers. With it we have more precise control over sharing, and we can always just float out or inline manually.
For more regular code, I believe there's nothing wrong with using Control.Monad.Loop or any other package that provides the functionality. Many Haskell users are not scrupulous about depending on small "fringe" libraries. We can also just reimplement for, in a desired generality. For instance, the following performs just as well as the other solutions:
for :: Monad m => a -> (a -> Bool) -> (a -> a) -> (a -> m ()) -> m ()
for init while step body = go init where
  go !i | while i = body i >> go (step i)
  go i = return ()
{-# INLINE for #-}

Looping in really constant space
I was at first very puzzled by the +RTS -s data on heap allocation. test_a allocated non-trivially with -fno-full-laziness, and also test_c without full laziness, and these allocations scaled linearly with the number of times iterations, but test_b with full laziness allocated only for the vector:
-- with -fno-full-laziness, no INLINE pragmas
test_a: 242,521,008 bytes
test_b: 121,008 bytes
test_c: 121,008 bytes -- but 240,120,984 with full laziness!

Also, INLINE pragmas for test_c did not help at all in this case.
I spent some time trying to find signs of heap allocation in the Core for the relevant programs, without success, until the realization struck me: GHC stack frames are on the heap, including the frames of the main thread, and the functions that were doing heap allocation were essentially running the thrice-nested loops in at most three stack frames. The heap allocation registered by +RTS -s is just the constant popping and pushing of stack frames.
This is pretty much apparent from the Core for the following code:
{-# OPTIONS_GHC -fno-full-laziness #-}

-- ...

test_a mvec =
    forM_ [0..times-1] $ \ n ->
        forM_ [0..side-1] $ \ y ->
            forM_ [0..side-1] $ \ x ->
                MV.unsafeWrite mvec (y*side+x) 1
main = do
    let vec = V.generate (side*side) (const 0)
    mvec <- V.unsafeThaw vec :: IO (MV.MVector (PrimState IO) Int)
    test_a mvec

Which I'm including here in its glory. Feel free to skip.
main1 :: State# RealWorld -> (# State# RealWorld, () #)
main1 =
  \ (s_a5HK :: State# RealWorld) ->
    case divInt# 9223372036854775807 8 of ww4_a5vr { __DEFAULT ->

    -- start of vector creation ----------------------
    case tagToEnum# (># 10000 ww4_a5vr) of _ {
      False ->
        case newByteArray# 80000 (s_a5HK `cast` ...)
        of _ { (# ipv_a5fv, ipv1_a5fw #) ->
        letrec {
          $s$wa_s8jS
            :: Int#
               -> Int#
               -> State# (PrimState IO)
               -> (# State# (PrimState IO), Int #)
          $s$wa_s8jS =
            \ (sc_s8jO :: Int#)
              (sc1_s8jP :: Int#)
              (sc2_s8jR :: State# (PrimState IO)) ->
              case tagToEnum# (<# sc1_s8jP 10000) of _ {
                False -> (# sc2_s8jR, I# sc_s8jO #);
                True ->
                  case writeIntArray# ipv1_a5fw sc_s8jO 0 (sc2_s8jR `cast` ...)
                  of s'#_a5Gn { __DEFAULT ->
                  $s$wa_s8jS (+# sc_s8jO 1) (+# sc1_s8jP 1) (s'#_a5Gn `cast` ...)
                  }
              }; } in
        case $s$wa_s8jS 0 0 (ipv_a5fv `cast` ...)
        -- end of vector creation -------------------

        of _ { (# ipv6_a4Hv, ipv7_a4Hw #) ->
        letrec {
          a2_s7MJ :: Int# -> State# RealWorld -> (# State# RealWorld, () #)
          a2_s7MJ =
            \ (x_a5Ho :: Int#) (eta_B1 :: State# RealWorld) ->
              letrec {
                a3_s7ME :: Int# -> State# RealWorld -> (# State# RealWorld, () #)
                a3_s7ME =
                  \ (x1_X5Id :: Int#) (eta1_XR :: State# RealWorld) ->
                    case ipv7_a4Hw of _ { I# dt4_a5x6 ->
                    case writeIntArray#
                           (ipv1_a5fw `cast` ...) (*# x1_X5Id 100) 1 (eta1_XR `cast` ...)
                    of s'#_a5Gn { __DEFAULT ->
                    letrec {
                      a4_s7Mz :: Int# -> State# RealWorld -> (# State# RealWorld, () #)
                      a4_s7Mz =
                        \ (x2_X5J8 :: Int#) (eta2_X1U :: State# RealWorld) ->
                          case writeIntArray#
                                 (ipv1_a5fw `cast` ...)
                                 (+# (*# x1_X5Id 100) x2_X5J8)
                                 1
                                 (eta2_X1U `cast` ...)
                          of s'#1_X5Hf { __DEFAULT ->
                          case x2_X5J8 of wild_X2o {
                            __DEFAULT -> a4_s7Mz (+# wild_X2o 1) (s'#1_X5Hf `cast` ...);
                            99 -> (# s'#1_X5Hf `cast` ..., () #)
                          }
                          }; } in
                    case a4_s7Mz 1 (s'#_a5Gn `cast` ...)
                    of _ { (# ipv2_a4QH, ipv3_a4QI #) ->
                    case x1_X5Id of wild_X1e {
                      __DEFAULT -> a3_s7ME (+# wild_X1e 1) ipv2_a4QH;
                      99 -> (# ipv2_a4QH, () #)
                    }
                    }
                    }
                    }; } in
              case a3_s7ME 0 eta_B1 of _ { (# ipv2_a4QH, ipv3_a4QI #) ->
              case x_a5Ho of wild_X1a {
                __DEFAULT -> a2_s7MJ (+# wild_X1a 1) ipv2_a4QH;
                99999 -> (# ipv2_a4QH, () #)
              }
              }; } in
        a2_s7MJ 0 (ipv6_a4Hv `cast` ...)
        }
        };
      True ->
        case error
               (unpackAppendCString#
                  "Primitive.basicUnsafeNew: length to large: "#
                  (case $wshowSignedInt 0 10000 ([])
                   of _ { (# ww5_a5wm, ww6_a5wn #) ->
                   : ww5_a5wm ww6_a5wn
                   }))
        of wild_00 {
        }
    }
    }

main :: IO ()
main = main1 `cast` ...

main2 :: State# RealWorld -> (# State# RealWorld, () #)
main2 = runMainIO1 (main1 `cast` ...)

main :: IO ()
main = main2 `cast` ...

We can also nicely demonstrate the allocation of frames the following way. Let's change test_a:
test_a mvec =
    forM_ [0..times-1] $ \ n ->
        forM_ [0..side-1] $ \ y ->
            forM_ [0..side-50] $ \ x -> -- change here
                MV.unsafeWrite mvec (y*side+x) 1

Now the heap allocation stays exactly the same, because the innermost loop is tail-recursive and uses a single frame. With the following change, the heap allocation halves (to 124,921,008 bytes), because we push and pop half as many frames:
test_a mvec =
    forM_ [0..times-1] $ \ n ->
        forM_ [0..side-50] $ \ y -> -- change here
            forM_ [0..side-1] $ \ x ->
                MV.unsafeWrite mvec (y*side+x) 1

test_b and test_c (with no full laziness) instead compile to code that uses a nested case construct inside a single stack frame, and walks over the indices to see which one should be incremented. See the Core for the following main:
{-# LANGUAGE BangPatterns #-} -- later I'll talk about this
{-# OPTIONS_GHC -fno-full-laziness #-}

main = do
    let vec = V.generate (side*side) (const 0)
    !mvec <- V.unsafeThaw vec :: IO (MV.MVector (PrimState IO) Int)
    test_c mvec

Voila:
main1 :: State# RealWorld -> (# State# RealWorld, () #)
main1 =
  \ (s_a5Iw :: State# RealWorld) ->
    case divInt# 9223372036854775807 8 of ww4_a5vT { __DEFAULT ->

    -- start of vector creation ----------------------
    case tagToEnum# (># 10000 ww4_a5vT) of _ {
      False ->
        case newByteArray# 80000 (s_a5Iw `cast` ...)
        of _ { (# ipv_a5g3, ipv1_a5g4 #) ->
        letrec {
          $s$wa_s8ji
            :: Int#
               -> Int#
               -> State# (PrimState IO)
               -> (# State# (PrimState IO), Int #)
          $s$wa_s8ji =
            \ (sc_s8je :: Int#)
              (sc1_s8jf :: Int#)
              (sc2_s8jh :: State# (PrimState IO)) ->
              case tagToEnum# (<# sc1_s8jf 10000) of _ {
                False -> (# sc2_s8jh, I# sc_s8je #);
                True ->
                  case writeIntArray# ipv1_a5g4 sc_s8je 0 (sc2_s8jh `cast` ...)
                  of s'#_a5GP { __DEFAULT ->
                  $s$wa_s8ji (+# sc_s8je 1) (+# sc1_s8jf 1) (s'#_a5GP `cast` ...)
                  }
              }; } in
        case $s$wa_s8ji 0 0 (ipv_a5g3 `cast` ...)
        of _ { (# ipv6_a4MX, ipv7_a4MY #) ->
        case ipv7_a4MY of _ { I# dt4_a5xy ->
        -- end of vector creation

        letrec {
          a2_s7Q6 :: Int# -> State# RealWorld -> (# State# RealWorld, () #)
          a2_s7Q6 =
            \ (x_a5HT :: Int#) (eta_B1 :: State# RealWorld) ->
              letrec {
                a3_s7Q5 :: Int# -> State# RealWorld -> (# State# RealWorld, () #)
                a3_s7Q5 =
                  \ (x1_X5J9 :: Int#) (eta1_XP :: State# RealWorld) ->
                    letrec {
                      a4_s7MZ :: Int# -> State# RealWorld -> (# State# RealWorld, () #)
                      a4_s7MZ =
                        \ (x2_X5Jl :: Int#) (s1_X4Xb :: State# RealWorld) ->
                          case writeIntArray#
                                 (ipv1_a5g4 `cast` ...)
                                 (+# (*# x1_X5J9 100) x2_X5Jl)
                                 1
                                 (s1_X4Xb `cast` ...)
                          of s'#_a5GP { __DEFAULT ->

                          -- the interesting part! ------------------
                          case x2_X5Jl of wild_X1y {
                            __DEFAULT -> a4_s7MZ (+# wild_X1y 1) (s'#_a5GP `cast` ...);
                            99 ->
                              case x1_X5J9 of wild1_X1o {
                                __DEFAULT -> a3_s7Q5 (+# wild1_X1o 1) (s'#_a5GP `cast` ...);
                                99 ->
                                  case x_a5HT of wild2_X1c {
                                    __DEFAULT -> a2_s7Q6 (+# wild2_X1c 1) (s'#_a5GP `cast` ...);
                                    99999 -> (# s'#_a5GP `cast` ..., () #)
                                  }
                              }
                          }
                          }; } in
                    a4_s7MZ 0 eta1_XP; } in
              a3_s7Q5 0 eta_B1; } in
        a2_s7Q6 0 (ipv6_a4MX `cast` ...)
        }
        }
        };
      True ->
        case error
               (unpackAppendCString#
                  "Primitive.basicUnsafeNew: length to large: "#
                  (case $wshowSignedInt 0 10000 ([])
                   of _ { (# ww5_a5wO, ww6_a5wP #) ->
                   : ww5_a5wO ww6_a5wP
                   }))
        of wild_00 {
        }
    }
    }

main :: IO ()
main = main1 `cast` ...

main2 :: State# RealWorld -> (# State# RealWorld, () #)
main2 = runMainIO1 (main1 `cast` ...)

main :: IO ()
main = main2 `cast` ...

I have to admit that I basically don't know why some code avoids stack frame creation and some doesn't. I suspect that inlining from "the inside" out helps, and a quick inspection informed me that Control.Monad.Loop uses a CPS encoding, which might be relevant here, although the Monad.Loop solution is sensitive to let floating, and I couldn't determine on short notice from the Core why test_c with let floating fails to run in a single stack frame.
Now, the performance benefit of running in a single stack frame is small. We've seen that test_b is only slightly faster than test_a. I include this detour in the answer because I found it edifying.
The state hack and strict bindings
The so-called state hack makes GHC aggressive in inlining into IO and ST actions. I think I should mention it here, because besides let floating this is the other thing that can thoroughly ruin performance.
The state hack is enabled with optimizations -O, and can possibly slow down programs asymptotically. A simple example from Reid Barton:
import Control.Monad
import Debug.Trace

expensive :: String -> String
expensive x = trace "$$$" x

main :: IO ()
main = do
  str <- fmap expensive getLine
  replicateM_ 3 $ print str

With GHC-7.10.2, this prints "$$$" once without optimizations but three times with -O2. And it seems that with GHC-7.10, we can't get rid of this behavior with -fno-state-hack (which is the subject of the linked ticket from Reid Barton).
Strict monadic bindings reliably get rid of this problem:
main :: IO ()
main = do
  !str <- fmap expensive getLine
  replicateM_ 3 $ print str

I think it's good habit to do strict bindings in IO and ST. And I have some experience (not definitive though; I'm far from being a GHC expert) that strict bindings are especially needed if we use -fno-full-laziness. Apparently full laziness can help get rid of some of the work duplication introduced by the inlining caused by the state hack; with test_b and no full laziness, omitting the strict binding on !mvec <- V.unsafeThaw vec caused a slight slowdown and extremely ugly Core output.


text:
Q: why my background is going in front of my text? why my background is going in front of my text?
so I have .html and .css file like this
I've tried postion relative, absolute, fixed but the output still not what I want.

    .main-main-container{
     position:absolute;
     display: grid;
     height: 100vh;
     margin:0;
     padding:0;

    }

    .main-container{
     display: grid;
     //grid-template-rows: minmax(20%,auto) auto minmax(20%,auto) minmax(10%,auto);
     grid-template-rows: 1fr 4fr 1fr 40px ;
     grid-gap: 0.5em;

    }

    /*
    @keyframes sliding-background{
     0%{
      background-image: url(../images/Desert.jpg);
     }
     25%{
      background-image: url(../images/Hydrangeas.jpg);
     }
     50%{
      background-image: url(../images/Jellyfish.jpg);
     }
     75%{
      background-image: url(../images/Lighthouse.jpg);
     }
     100%{
      background-image: url(../images/Penguins.jpg);
     }

    }
    */

    .main-container > figure {
     animation: imageAnimation 30s linear infinite 0s;
     backface-visibility: hidden;
     background-size: cover;
     background-position: center center;
     color: transparent;
     height: 100%;
     left: 0px;
     opacity: 0;
     position: absolute;
     top: 0px;
     width: 100%;
     z-index: 0;
     margin:0;
     padding:0;
    }
    .main-container > figure:nth-child(1) {
     background-image: url('../images/Desert.jpg');
    }
    .main-container > figure:nth-child(2) {
     animation-delay: 6s;
     background-image: url('../images/Hydrangeas.jpg');
    }
    .main-container > figure:nth-child(3) {
     animation-delay: 12s;
     background-image: url('../images/Jellyfish.jpg');
    }
    .main-container > figure:nth-child(4) {
     animation-delay: 18s;
     background-image: url('../images/Lighthouse.jpg');
    }
    .main-container > figure:nth-child(5) {
     animation-delay: 24s;
     background-image: url('../images/Penguins.jpg');
    }

    @keyframes imageAnimation {
     0% {
      animation-timing-function: ease-in;
      opacity: 0;
     }
     8% {
      animation-timing-function: ease-out;
      opacity: 1;
     }
     17% {
      opacity: 1
     }
     25% {
      opacity: 0
     }
     100% {
      opacity: 0
     }
    }

    .header-container {
     display: grid;
     grid-template-columns: 1fr 2fr 1fr;
     //background: red;

    }

    .content-container {
     display: grid;
     grid-template-columns: 1fr 2fr 1fr;
     //background: yellow;
    }

    .subcontent-container {
     display: grid;
     grid-template-columns: 1fr 2fr 1fr;
     //background: green;
    }

    .header-container > div,
    .content-container > div,
    .subcontent-container > div{
     border: #222 1px solid;
    }

    .content{
     //background: green;
    }

    .sub-content{
     //background: yellow
    }

    .footer-container{
     //background: pink;
     border: #222 1px solid;

    }

        Lorem ipsum dolor sit amet.

        Lorem ipsum dolor sit amet, consectetur adipisicing elit. Asperiores, quis ducimus sed in exercitationem quae, molestias placeat eius eveniet molestiae repellendus animi dignissimos, non nostrum facere id iste fugit aspernatur est perferendis? Eaque tempora nesciunt deleniti voluptatem ad quisquam voluptatum.

        Lorem ipsum dolor sit amet.

        Lorem ipsum dolor, sit amet consectetur adipisicing elit. Dolorem amet maiores, voluptatem quibusdam et veritatis repellendus reiciendis dolor facilis assumenda.

        Lorem ipsum dolor, sit amet consectetur adipisicing elit. Dolorem amet maiores, voluptatem quibusdam et veritatis repellendus reiciendis dolor facilis assumenda.

        Lorem ipsum dolor, sit amet consectetur adipisicing elit. Dolorem amet maiores, voluptatem quibusdam et veritatis repellendus reiciendis dolor facilis assumenda.

        Lorem ipsum dolor sit amet consectetur adipisicing elit. Quaerat, nam.

        Lorem ipsum dolor sit amet consectetur adipisicing elit. Quaerat, nam.

        Lorem ipsum dolor sit amet consectetur adipisicing elit. Quaerat, nam.

        Lorem ipsum dolor sit amet.

what I want is my sliding-figure is in the back of my text so its become my background image not replacing my text in front of it.

A: .main-container > figure {
    animation: imageAnimation 30s linear infinite 0s;
    backface-visibility: hidden;
    background-size: cover;
    background-position: center center;
    color: transparent;
    height: 100%;
    left: 0px;
    opacity: 0;
    position: absolute;
    top: 0px;
    width: 100%;
    z-index: -3;
    margin:0;
    padding:0;
}

A: .main-container > figure{
    z-index: -1;
}

working Fiddle
I think this will make it work.


text:
Q: How to include custom data in a point data of arearange chart I am creating an arearange chart in Highcharts. Data to this chart is passed as an array of array like [[1,2,3],..]. Can i pass custom data in this point like [[1,2,3, "abc:12"],[5,6,7,"abc:14"]..].
If i want to pass custom data for each point, please let me know how to pass.

A: You can use keys property to map the values and for example use the custom value in a tooltip:
Highcharts.chart('container', {
    series: [{
        keys: ['x', 'low', 'high', 'customValue'],
        type: 'arearange',
        data: [
            [1, 2, 3, "abc:12"],
            [5, 6, 7, "abc:14"]
        ]
    }],
    tooltip: {
        pointFormat: '{point.customValue}'
    }
});

Live demo: http://jsfiddle.net/BlackLabel/ncmy1jt7/
API Reference: https://api.highcharts.com/highcharts/series.arearange.keys
Or define the series data as an array of objects:
series: [{
    keys: ['x', 'low', 'high', 'customValue'],
    type: 'arearange',
    data: [{
        x: 1,
        low: 2,
        high: 3,
        customValue: "abc:12"
    }, {
        x: 5,
        low: 6,
        high: 7,
        customValue: "abc:14"
    }]
}]

Live demo: http://jsfiddle.net/BlackLabel/s035q8um/


text:
Q: Bug in Matlab implementation of Porter Stemmer I use the Matlab implementation of the Porter Stemming algorithm published here. When I use it on a large portion of text, I get an error message when the string "ies" is passed in.
>> porterStemmer('ies')

I get the error message:
Subscript indices must either be real positive integers or
logicals.

Error in porterStemmer>step2 (line 274)
switch b(k-1)

Error in porterStemmer (line 42)
    x = step2(x{1}, x{2}, k0);

I suppose it might be, because "ies"is a common word ending and also appears in the script on line 223 as elseif ends('ies', b, k).
I was expecting the program to be robust to cases like this. Was I wrong to think that or this is a bug?
For the time being, I've resorted to using the Porter Stemmer 2 (here), which doesn't throw an error and stems "ies" to "ie". Stemming "ies" is a bit pointless obviously, but I'd rather not have it throw errors in edge cases like this.


text:
Q: Using Sass compressed output while leaving theme comment header for Wordpress How do other Wordpress theme developers incorporate Sass into their theme development while taking advantage of its compressed output style? Sass compressed removes ALL comments, so I currently have an empty style.css with my theme declaration and an @import calling the minified css from compass, but this hardly seems like the best solution.
Has anybody found a way around this? What would be the best solution if not?
http://codex.wordpress.org/Theme_Development#Theme_Stylesheet
http://sass-lang.com/docs/yardoc/file.SASS_REFERENCE.html#id40

A: SUPER SHORT VERSION: Use /*! loud comments */ and compile the SCSS just before packaging and distributing.
Two part answer, "old part" first:
I used Sass/SCSS when developing my "Orin" theme: https://github.com/founddrama/orin
Part One:

*

*In my src/scss directory, I keep all of my _include.scss files and the style.scss file that has all of the @import statements.

*During development, I just run the usual sass --watch (although it's an extra step to remember to save the style.scss file).

*Once your SCSS source is looking good and committed to version control, you can simply build the style.scss into style.css and check that into version control for the Theme that gets distributed.

In my case, "Orin" is just for me, so I perform the build when I update it on the blog server, but the SCSS compilation can just as easily be done prior to packaging/distribution. The build script I'm using is here (in that Github repo); the gist of it being:

*

*touch to create the style.css output file;

*apply the license text;

*compile the SCSS and append it to style.css.

Part Two:
More recent versions of Sass include support for /*! loud comments */; meaning that I need to get off my lazy butt and update to:

*

*Include the license text and theme description right there in style.scss using the loud comments;

*update the build/deploy script to simply compile the SCSS.

A: Well, i would suggest you to use Compass .
The comment should look like this:
/*! A loud SASS comment */


text:
Q: fail sending non-premitive param with angularjs stateParams I have this angular-js template:
<md-content layout="row" layout-align="center center">

search results

        <md-card flex="60" ng-repeat="voice in $ctrl.voices" ng-click="$ctrl.editVoice($index)">
            <md-card-title>
                <md-card-title-text>

...

I have this angular-js code:
app.component('voiceFormComponent', {
        templateUrl: 'partials/voice-form.html',
        controller:  ['$state', '$stateParams', '$http',
            function ($state, $stateParams, $http) {

                var self = this;
                console.log("in voice prompt component");

                var isVoiceUndefined = $stateParams.voice === undefined;

when the template sends onClick(1) and there are 3 elements in "voices" array.
how come I always get $stateParams.voice === undefined?

A: you must define all paramters in states config, then you can use i.e. $state.go('state', {param: anyObject})


text:
Q: Is it possible to extend the inner product from an incomplete inner product space E onto H ,such that H would become a Hilbert space? Let E be an incomplete inner product space. Let H be the completion
of E . Is it possible to extend the inner product from E
onto H such that H would become a Hilbert space?
I think the answer is to establish with continuity of the inner product but do not know how to show?

A: We can use the fact that every uniformly-continuous function defined on a dense subset extends continuously onto a complete metric space. A non-complete metric space is a dense subset of its completion, and the inner-product is uniformly-continuous on the "pre-complete" space.


text:
Q: Properly aligned appendix in ToC I'm trying to write my own class and while I'm didn't use hyperref package following code work properly.
\newcommand\chaptindent{\advance\leftskip 1.0em \hskip -\leftskip}
\newcommand\appenindent{\advance\leftskip 6.0em \hskip -\leftskip}

\def\@chapter[#1]#2{
  \ifnum \c@secnumdepth > \m@ne
    \if@mainmatter
       \refstepcounter{chapter}%
       \addcontentsline{toc}{chapter}%
           {\chaptindent\protect\numberline{\thechapter}\MakeUppercase{#1}}%
    \else
       \refstepcounter{chapter}
       \addcontentsline{toc}{chapter}%
           {\appenindent\nobreak\@chapapp\space\protect\numberline{
                \thechapter}\space{#1}}
    \fi
  \else
    \addcontentsline{toc}{chapter}{\MakeUppercase{#1}}%
  \fi
    \chaptermark{#1}%
    \addtocontents{lof}{\protect\addvspace{10\p@}}%
    \addtocontents{lot}{\protect\addvspace{10\p@}}%
    \@makechapterhead{#2}%
    \@afterheading}

After I had include hyperref package the appendix ToC lines moved over left border.

Removed \chaptindent and \appenindent from \@chapter redifinition and got ToC without any standoff

Try to fix this issue with \def\l@chapter{\@dottedtocline{1}{0.0em}{1.0em}} command but there are the same indent for chapter and appendix lines.

How can I get Properly ToC appendix aligned with using hyperref package?

A: I have solved this problem. So there is solution which may be useful for someone.
Appendices are the same chapters and, so for showing them in table of contents uses same
command as for chapters and it's \l@chapter. This command is formed while \contentsline{chapter}{...
items handling.For differentiate chapters and appendices needs to form different \contentsline items in
.toc file, as follow \contentsline{chapter}{... and \contentsline{appendix}{.... For handling
\contentsline{appendix}{... it have been needed to implement \l@appendix command. After this I got
opportunity to separate handling for chapters and appendices whereas table of contents is forming.
\def\@chapter[#1]#2{\ifnum\c@secnumdepth>\m@ne%
                    \if@mainmatter%
                      \refstepcounter{chapter}%
                      \addcontentsline{toc}{chapter}%
    {\protect\numberline\thechapter\texorpdfstring{\MakeUppercase{#1}}{#1}}%
                    \else%
                      \refstepcounter{chapter}%
                      \phantomsection
                      \addcontentsline{toc}{appendix}%
    {\texorpdfstring{\@chapapp\space\protect\numberline\thechapter\space#1}
     {\@chapapp\space\thechapter\space#1}}%
                    \fi%
                    \else%
                      \addcontentsline{toc}{chapter}{#1}%
                    \fi%
                      \chaptermark{#1}%
                      \addtocontents{lof}{\protect\addvspace{10\p@}}%
                      \addtocontents{lot}{\protect\addvspace{10\p@}}%
                      \@makechapterhead{#2}%
                      \@afterheading}

So this code generate following .toc file content
...
\contentsline {chapter}{\numberline 2\MakeUppercase {\IeC ...
...
\contentsline {appendix}{{\Ukrainian \CYRD ...

which is handled by two commands
\renewcommand\l@chapter[2]{%
   \ifnum \c@tocdepth >\m@ne
    \vskip \z@ \@plus.2\p@
    {\leftskip 0.0em\relax \rightskip \@tocrmarg plus 15em \parfillskip -
  \rightskip%mod <plus 15em> for avoid hyph. in TOC
     \parindent 0.0em\relax\@afterindenttrue
     \interlinepenalty\@M
     \leavevmode
     \@tempdima 1.0em\relax
     \advance\leftskip \@tempdima \null\nobreak\hskip -\leftskip
     {#1}\nobreak
     \leaders\hbox{$\m@th
      \mkern \@dotsep mu\hbox{.}\mkern \@dotsep
         mu$}\hfill
      \nobreak
     \hb@xt@\@pnumwidth{\hfil \normalcolor #2}%   \hfil\normalfont   |||
    \par}%
   \fi}

\newcommand\l@appendix[2]{%
  \ifnum \c@tocdepth >\m@ne
    \vskip \z@ \@plus.2\p@
    {\leftskip 0.0em\relax \rightskip \@tocrmarg plus 15em \parfillskip -
 \rightskip%mod <plus 15em> for avoid hyph. in TOC
     \parindent 0.0em\relax \hangindent 4.3em\relax\@afterindenttrue
     \interlinepenalty\@M
     \leavevmode
     \@tempdima 1.5em\relax
     \advance\leftskip \@tempdima \null\nobreak\hskip -\leftskip
     {#1}\nobreak
     \leaders\hbox{$\m@th
        \mkern \@dotsep mu\hbox{.}\mkern \@dotsep
       mu$}\hfill
     \nobreak
     \hb@xt@\@pnumwidth{\hfil \normalcolor #2}%   \hfil\normalfont   |||
     \par}%
  \fi}

\phantomsection used for hyperref links works correct.


text:
Q: LDA, Significance of orthonormality- Trace Ratio Maximization The objective of fisher linear discriminant analysis can be formulated as maximizing $\frac{Tr[X^TAX]}{Tr[X^TBX]}$ over $X$ where $A$ and $B$ are positive semi-definite with orthonormality constraints over X.
What is the significance of the orthonormality constraint in  here?
I am also curious if reformulating this objective as $Tr[X^TAX]-\alpha Tr[X^TBX]$ is justified? $\alpha$ belongs to positive reals and the objective is a function of $X$ and $\alpha$ in this case.
Was reading section II in : http://www.eecs.berkeley.edu/~jiayq/papers/tnn_traceratio.pdf and was wondering about the orthonormality constraint. I believe that orthonormality constraints in some trace minimization problems prevent a trivial solution, where the entries in X can all go to zero. The objective for Fisher's LDA seems to be having the orthonormality constraint for quite a different reason, and am not sure about it. Has it got do to something with a unique solution over rotation matrices? I don't believe that to be true either..


text:
Q: Gnuplot: How to restrict multiple parametric plots to different ranges? I want to plot three parametric curves where each of them has a different range.
I checked the demo script page and the 9th plot demonstrates what I want to do. However, this does not work for my code:
set parametric
#set urange [0:2*pi]
#set vrange[0.3*pi:pi]
# Parametric functions for the sphere
set samples 1000
wplus = 20
wminus = 1
wz = 10
# 0 = one large circle
rhoplus0 = 0
rhominus0 = 10
rhoz0 = 0
fx0(u) = rhoplus0*cos(wplus*u) + rhominus0*cos(wminus*u)
fy0(u) = -rhoplus0*sin(wplus*u) - rhominus0*sin(wminus*u)
fz0(u)   = rhoz0*cos(wz*u)
# 1 = axial oscillation
rhoplus1 = 0
rhominus1 = 10
rhoz1 = 5
fx1(u) = rhoplus1*cos(wplus*u) + rhominus1*cos(wminus*u)
fy1(u) = -rhoplus1*sin(wplus*u) - rhominus1*sin(wminus*u)
fz1(u)   = rhoz1*cos(wz*u)
# 2 = many small circles
rhoplus2 = 2
rhominus2 = 10
rhoz2 = 0
fx2(u) = rhoplus2*cos(wplus*u) + rhominus2*cos(wminus*u)
fy2(u) = -rhoplus2*sin(wplus*u) - rhominus2*sin(wminus*u)
fz2(u)   = rhoz2*cos(wz*u)
splot [u=0:2*pi] fx0(u),fy0(u),fz0(u),\
      [u=pi:2*pi] fx1(u),fy1(u),fz1(u), \
      [u=0:pi] fx2(u),fy2(u),fz2(u)

The plot only ever takes the last range in u, in my case[u=0:pi]:
see image
I also checked this question, however, it did not solve my issue.
What am I doing wrong?

A: Both the demo plot and the previous answered question that you reference provide examples of plots similar to yours, together with some explanation.
The key point is to not use parametric mode. Instead revise your splot command to use either the 1-dimensional sampling 'pseudo-file' + or the 2-dimensional 'pseudo-file' ++.  The conventional sampling variable is t in the 1D case, u and v in the 2D case.  Here is a trivial example:
# parametric mode
set parametric
set trange [0 : 2*pi]
splot fx(t), fy(t), fz(t)

# equivalent plot using pseudo-file '+'
unset parametric
set trange [0 : 2*pi]
splot '+' using (fx(t)) : (fy(t)) : (fz(t))

In both of the above plots, the number of points plotted is taken from the default sampling size (100), which can be changed using the set sample command.  The samples are drawn evenly to span trange.
There is an additional wrinkle to consider if instead of using a prior set trange command you move the sampling description into the plot command.  In this case the sampling specification [t= <start> : <end> : <increment>] is limited to integer values. You can think of t as being an index into an array of samples.  In your case the simplest way to do this is switch from radians to degrees.  [t=0:360] would generate 361 samples (rather than the 100 we got before). [t=0:360:4] would generate 91 samples, etc.
So your revised plot command is going to look something like this:
set angle degrees
splot sample [t=0:360:2]   using (fx0(t)) : (fy0(t)) : (fz0(t)),\
             [t=180:360:1] using (fx1(t)) : (fy1(t)) : (fz1(t)), \
             [t=0:180:1]   using (fx2(t)) : (fy2(t)) : (fz2(t))

This gives you 181 samples for each plot component even though they have different size ranges.  If you require a larger number of samples (your example used set sample 1000) you would have to further modify the command, e.g.:
sample [t=0:3600:20] using (fx0(t/10.)) : (fy0(t/10.)) : (fz0(t/10.))

That should get you started.  If you revise your code along those lines and it still does not work, please update the question to show the revised code and describe what isn't working.


text:
Q: Node.js: Extract data from JSON response I'm fetching product details using an API which gives the response as a JSON object.
{
    "productBaseInfo": {
        "productIdentifier": {
            "productId": "EKTDDD23232zYHR94E4",
        },
        "productAttributes": {
            "title": "Nova KT 72BC 1 Electric Kettle",
            "imageUrls": {
                "400x400": "http://img5a.flixcart.com/image/electric-kettle/4/e/4/nova-kt-722-c-kt-722c-400x400-imadddh2fdvuzpxz.jpeg",
                "75x75": "http://img6a.flixcart.com/image/electric-kettle/4/e/4/nova-kt-722-c-kt-722c-75x75-imadddh2fdvuzpxz.jpeg",
            },
            "sellingPrice": {
                "amount": 599.0,
                "currency": "INR"
            },
            "productUrl": "http://dl.mykart.com/dl/nova-kt-722c-1-electric-kettle/p/itmdddf398rhhhz2?pid=EKTDDDEGXYHR94E4&affid=userid"
        }
    }
}

Now I want to get the productId, title in ProductAttributes, and all the image urls and productURL.
I tried
var productURL = JSON["productAttributes"].productUrl

But it returns an error productUrl not found error. Looking for suggestion on how to extract the data. Thanks in advance.

A: productAttributes is inside productBaseInfo. So you need to access it like this
console.log(JSON.productBaseInfo.productAttributes.productUrl);
// http://dl.mykart.com/dl/nova-kt-722c-1-electric-kettle/p/itmdddf398rhhhz2?pid=EKTDDDEGXYHR94E4&affid=nikhilgeo


text:
Q: Ruby Rails: Control flow in the basic blog application I am a total newbie to ruby rails, and i went through the basic tutorial and a sample blogging application with postgresql backend, in the link. Although i kind of got the gist of it, i really didnt understand how the application accesses the postgresql at the backend and also didnt understand the application flow and few keywords which occur in the controller and view files, for example the below line which appears in the index.html.erb file.
 <%= link_to 'Edit', edit_post_path(post) %>

For instance, i didnt understand the edit_post_path(post) keyword. Can someone please point me to a good source for understanding the very basics of rails?

A: Welcome to the Rails developer community!
Resources:

*

*Ruby on Rails Guide

*Getting Started RailsCast

MVC
The core principle of Rails is it's a full-stack MVC framework
MVC = Model - View - Controller

If you can learn how this works, it will be the foundation knowledge you need to make good progress. Rails does not work like "standard" websites -- it's a full blown application development framework which works with the MVC principle:

Data
The "flow" of data through an MVC application centers on the user
The user requests a page (by typing / clicking on a Rails route), the request is sent to a controller, which may pull data from the model. The data is kept in an external database (can be MYSQL / PGSQL / anything), and works by connecting through a gem
Your job as a developer is to make sure the user is presented with the correct data & options at the right time

Question
<%= link_to 'Edit', edit_post_path(post) %>

This is a link to the edit post path, which will be defined in your config/routes.rb file. This path will load up this file / method:
#app/controllers/posts_controller.rb
def edit
    #your code
end

This will then render a particular view file for your users to use. There's a lot more to explain other than this, but I hope this gives you the help you need


text:
Q: fireCustomEvent is undefined I'm getting error saying Uncaught TypeError: Cannot read properties of undefined (reading 'fireCustomEvent'). Please help how to resolve this as I'm making use of Oracle JET to write this javascript code
define([], () => {
  'use strict';

  //var eventHelper;
  var idleTime = 0;

  class PageModule {
    constructor(context) {
      this.eventHelper = context.getEventHelper();

      // Increment the idle time counter every minute.
      this.idleInterval = setInterval(this.timerIncrement, 5000); // 10 second
    }

    timerIncrement() {
      console.log(idleTime);
      idleTime = idleTime + 1;
      if (idleTime > 0) {
        console.log(this.eventHelper);
        this.eventHelper.fireCustomEvent('openDialog', {});
      }
    }

  }

  // Zero the idle timer on mouse movement.
  $(this).mousemove(function (e) { idleTime = 0; });
  $(this).keypress(function (e) { idleTime = 0; });

  return PageModule;
});

A: This issue may be related to Referencing "this" inside setInterval/setTimeout.
With the current code, after transpile, the PageModule will be
var PageModule = /** @class */ (function () {
    function PageModule(context) {
        //.....
        this.idleInterval = setInterval(this.timerIncrement, 5000); // 10 second
    }
    PageModule.prototype.timerIncrement = function () {
        if (idleTime > 0) {
            console.log(this.eventHelper);
            this.eventHelper.fireCustomEvent('openDialog', {});
        }
    };
    return PageModule;
}());

this is not referring to PageModule but Window object of browser inside the timerIncrement function and because of that the eventHelper is undefined.
Solution 1: Use an arrow function.
const timerIncrement = () => {
    //....
    if (idleTime > 0) {
        console.log(this.eventHelper);
        this.eventHelper.fireCustomEvent('openDialog', {});
    }
}

Solution 2:
Pass this to timerIncrement as given below and use as self inside the timerIncrement function.
constructor(context) {
    this.idleInterval = setInterval(this.timerIncrement, 5000, this);
}

timerIncrement(self) {
    //....
    if (idleTime > 0) {
        console.log(self.eventHelper);
        self.eventHelper.fireCustomEvent('openDialog', {});
    }
}


text:
Q: Starting vehicle on hot days Why it is easy to start the vehicle on hot day than on cold days?
Since on winter days it is diffcult to start than on hot days I thought it is due to the low temperature which in turn affects the chemical reaction in the cell.Since energy is produced in the cell due to reaction.But I don't think it is the correct one..

A: There are two main reasons
As temperature is decreased the voltage of a car battery decreases and it's internal resistance increases. This means the battery can supply less current.
As temperature is decreased the viscosity of oil in the engine increases so the engine is harder to turn over.
In the days before fuel injection there was a third factor because carburettors are less good at vaporising fuel at low temperatures, but this won't be a problem for most modern cars.

A: Well in winter day's the cylinder's in which combustion takes place and the fuel as well as surrounding air are at very low temperature so when you start the engine the cold fuel and air mixture enters the cold combustion chamber and at that time the temperature of the spark produced by the spark plug for a very little instance of time is not sufficient to rise the temperature of the fuel gas mixture to the level at which it can burn and start the engine. Well after sometime you see that engine just start's and shut's down. I think this is because when the fuel burn and start expanding the heat is instantly absorbed by the cylinder walls and it stop's the expansion of the gas due to which piston is not able to move and engine don't start.


text:
Q: apache start using service - httpd process sleeping We have a lot of httpd process in aws webserver that are sleep and maintains a connection with mysql database in another server.   Connections are in sleep state in db server for a long time.  we start the apache server using service httpd restart.   why the httpd process are running as DFOREGROUND .  Want to run the httpd process in background how to do it and not sure so many process are sleeping.
319:apache   29542  8044  0 09:00 ?        00:00:03 /usr/sbin/httpd -DFOREGROUND
320:apache   30274  8044  0 09:04 ?        00:00:03 /usr/sbin/httpd -DFOREGROUND
321:apache   30461  8044  0 09:05 ?        00:00:03 /usr/sbin/httpd -DFOREGROUND
322:apache   31575  8044  0 09:11 ?        00:00:04 /usr/sbin/httpd -DFOREGROUND
323:apache   31581  8044  0 09:11 ?        00:00:04 /usr/sbin/httpd -DFOREGROUND
324:apache   31994  8044  0 09:12 ?        00:00:04 /usr/sbin/httpd -DFOREGROUND
325:apache   31996  8044  0 09:12 ?        00:00:03 /usr/sbin/httpd -DFOREGROUND


text:
Q: issues with skrollr on element with overflow: scroll I'm trying to make a nifty single page with some animations with the help of skrollr. For a very simple example, there are three slides, the slides are just fixed positioned at 100% width and height, the last one has an overflow: auto on it so one can scroll its content that doesn't need any animation and might not need more than 100% height eg. about, contact us and footer sections.
My understanding is that I can use skrollr to set opacity 0 or a display none on an element. The first and second have a higher z-index than the third so hiding the first two should have the third one show up automatically.
I used jQuery to confirm that

$('.slide1, .slide2').css('opacity', 0);

It works fine and the third container shows up while the rest are not visible. With skrollr though, in all other browsers but ff, it scrolls as intended with the trackpad on my macbook but doesn't scroll when using the browser's scrollbar. it's acting as if it's in overflow: hidden.

skrollr.init();
* {
  padding: 0;
  margin: 0;
}

section {
  color: #fff;
  padding: 25px;
}

header {
  position: fixed;
  z-index: 8;
}

.slide1,
.slide2,
.slide3 {
  position: fixed;
  width: 100%;
  height: 100%;
}

.slide1 {
  z-index: 7;
  background: green;
}

.slide2 {
  z-index: 6;
  background: blue;
}

.slide3 {
  z-index: 5;
  background: yellow;
  overflow: scroll;
}
<!DOCTYPE html>

                Slide 1

                scroll?

                scroll?

                scroll?

                scroll?

                scroll?

                scroll?

                scroll?

                scroll?

                scroll?

                scroll?

                scroll?

                scroll?

                scroll?

                scroll?

                scroll?

                scroll?

                scroll?

                scroll?

                scroll?

                scroll?

                scroll?

                scroll?

                scroll?

                scroll?

                scroll?

                scroll?

                scroll?

                scroll?

                scroll?

                scroll?

                scroll?

                scroll?

                scroll?

                scroll?

                scroll?

                scroll?

                scroll?

                scroll?

                scroll?

                scroll?

                scroll?

                scroll?

                scroll?

                scroll?

                scroll?

                scroll?

                scroll?

                scroll?

                scroll?

                scroll?

                scroll?

                scroll?

                scroll?

                scroll?

                scroll?

                scroll?

                scroll?

                scroll?

                scroll?

                scroll?

                scroll?

                scroll?

                scroll?

                scroll?

                scroll?

                scroll?

                scroll?

                scroll?

                scroll?

                scroll?

                scroll?

                scroll?

                scroll?

                scroll?

                scroll?

                scroll?

                scroll?

                scroll?

                scroll?

                scroll?

                scroll?

                scroll?

                scroll?

                scroll?

                scroll?

                scroll?

                scroll?

                scroll?

                Slide 2

                scroll?

                scroll?

                scroll?

                scroll?

                scroll?

                scroll?

                scroll?

                scroll?

                scroll?

                scroll?

                scroll?

                scroll?

                scroll?

                scroll?

                scroll?

                scroll?

                scroll?

                scroll?

                scroll?

                scroll?

                scroll?

                scroll?

                scroll?

                scroll?

                scroll?

                scroll?

                scroll?

                scroll?

                scroll?

                scroll?

                scroll?

                scroll?

                scroll?

                scroll?

                scroll?

                scroll?

                scroll?

                scroll?

                scroll?

                scroll?

                scroll?

                scroll?

                scroll?

                scroll?

                scroll?

                scroll?

                scroll?

                scroll?

                scroll?

                scroll?

                scroll?

                scroll?

                scroll?

                scroll?

                scroll?

                scroll?

                scroll?

                scroll?

                scroll?

                scroll?

                scroll?

                scroll?

                scroll?

                scroll?

                scroll?

                scroll?

                scroll?

                scroll?

                scroll?

                scroll?

                scroll?

                scroll?

                scroll?

                scroll?

                scroll?

                scroll?

                scroll?

                scroll?

                scroll?

                scroll?

                scroll?

                scroll?

                scroll?

                scroll?

                scroll?

                scroll?

                scroll?

                scroll?

                Slide 3

                scroll?

                scroll?

                scroll?

                scroll?

                scroll?

                scroll?

                scroll?

                scroll?

                scroll?

                scroll?

                scroll?

                scroll?

                scroll?

                scroll?

                scroll?

                scroll?

                scroll?

                scroll?

                scroll?

                scroll?

                scroll?

                scroll?

                scroll?

                scroll?

                scroll?

                scroll?

                scroll?

                scroll?

                scroll?

                scroll?

                scroll?

                scroll?

                scroll?

                scroll?

                scroll?

                scroll?

                scroll?

                scroll?

                scroll?

                scroll?

                scroll?

                scroll?

                scroll?

                scroll?

                scroll?

                scroll?

                scroll?

                scroll?

                scroll?

                scroll?

                scroll?

                scroll?

                scroll?

                scroll?

                scroll?

                scroll?

                scroll?

                scroll?

                scroll?

                scroll?

                scroll?

                scroll?

                scroll?

                scroll?

                scroll?

                scroll?

                scroll?

                scroll?

                scroll?

                scroll?

                scroll?

                scroll?

                scroll?

                scroll?

                scroll?

                scroll?

                scroll?

                scroll?

                scroll?

                scroll?

                scroll?

                scroll?

                scroll?

                scroll?

                scroll?

                scroll?

                scroll?

                scroll?

http://codepen.io/anon/pen/aZvRWw
bug? not what it was intended for? easier way of doing this? workarounds? I don't want to have to look into a seperate library just to do the same thing.

A: The issue I'm seeing when reviewing in Chrome, FF, and Safari is that when the scrollbar reaches the 3rd slide, it starts to scroll the content in that slide only. So the scrollbar functionality will only scroll within that container (when not using the trackpad).
Edit: since the third slide will need to be independently scrollable, it can't be position: fixed. Instead, we'll make it absolute like so:
.slide3 {
  position: absolute;
  top: 200%;
  left: 0;
  height: auto;
  width: 100%;
}

And remove the skrollr definitions on that slide, as well. Since it's positioned relative to the body, we can add the top: 200% property and know that it will appear once the first two 100% sections are finished scrolling. This also allows the use of the scrollbar through the full animation sequence.
Here's an updated codepen with both of those fixes added:
http://codepen.io/thecox/pen/PzPxYo
Let me know if you're trying to accomplish something different, and I can add some additional information.


text:
Q: Need to make sure I interpreted the question correctly (I fixed the question I need some upvotes to lay off my question ban) Define a class for a type called CounterType. An object of this type is used to count
things, so it records a count that is a nonnegative whole number.
a. Private data member: count.
b. Include a mutator function that sets the counter to a count given as an argument.
c. Include member functions to increase the count by one and to decrease the count
by one.
d. Include a member function that returns the current count value and one that outputs
the count.
e. Include default constructor that set the count to 0.
f. Include one argument constructor that set count to given argument.
Be sure that no member function allows the value of the counter to become negative.
Embed your class definition in a test program.
An output example would be:
a = CounterType(10)
a.display()
a.increase()
a.display()
a.setCounter(100)
a.display

Will display the following:
Counter: 10
Counter: 11
Counter: 100

I have written the code but I just want to make sure that it is following what the question asked and if there could be an easier way to write this code.
class CounterType:
  def __init__(self, counter=0):
    self.counter = counter
  def increase(self):
    self.counter += 1
  def decrease(self):
    if self.counter == 0:
      print("Error, counter cannot be negative")
  else:
    self.counter -= 1
  def setCounter(self, x):
    if x < 0:
      print("Error, counter cannot be negative")
    else:
      self.counter = x
  def setCount0(self):
    self.counter = 0
  def display(self):
    print("Counter:", self.counter)
  def getCounter(self):
    return self.counter

This is a homework assignment so it would help if you could just give some tips

A: You forgot "Be sure that no member function allows the value of the counter to become negative."
The naïve way to do this is to add an if condition in every function. A smarter way would be to add that check the setCounter function and use this function from all other functions.
class CounterType:

  def __init__(self, counter=0): # (e, f) counter = 0: default argument value so x = CounterType() works and has a counter of 0
    self.counter = 0  # (a)
    self.setCounter(counter)

  def increase(self): # (c)
    self.setCounter(self.counter + 1)

  def decrease(self): # (c)
    self.setCounter(self.counter - 1)

  def setCounter(self, x): # (b)
    if x < 0:
      print("Error, counter cannot be negative")
    else:
      self.counter = x

  def setCount0(self): # This is not needed
    self.counter = 0

  def display(self): # (d)
    print("Counter:", self.counter)

  def getCounter(self): # (d)
    return self.counter


text:
Q: Passing JSON Array from Javascript to Web API Controller method I was not able to get the JSON array parameters in web api controller method (SaveDetails).
Here are my code.
JavaScript Code:
  $.ajax(
    {
        url  : "api/Test/SaveDetails",
        type : "POST",
        data : {
                    "employees":
                    [
                        { "firstName": "John", "lastName": "Doe" },
                        { "firstName": "Anna", "lastName": "Smith" },
                        { "firstName": "Peter", "lastName": "Jones" }
                    ]
                },
        success: function (data) {alert("success");},
        error: function () {alert("Error");}
    })

Controller method
[HttpPost]
public DataSet SaveDetails(Models.Person[] obj)
{
    //save opertion.
}

Model Method:
 public class Person
{
    public string firstName { get; set; }
    public string lastName { get; set; }
}

What are the changes to be made to get the JSON array parameters in web api method.

A: I ran across this thread when searching for an answer to my problem, trying to pass a list/array of object to a web api controller.
Details at this link:
https://kwilson.io/blog/post-an-array-of-objects-to-webapi-using-jquery/

Change your data to be a single anonymous object instead of a raw array and it'll work.

So in your case you might do the following for your data
data : {
                "":
                [
                    { "firstName": "John", "lastName": "Doe" },
                    { "firstName": "Anna", "lastName": "Smith" },
                    { "firstName": "Peter", "lastName": "Jones" }
                ]
            },

And in your Web API controller
[HttpPost]
public DataSet SaveDetails(List<Models.Person> obj)
{
    //save operation.
}

This way you don't have to create another class to hold a list object like in Veera's answer.

A: Try the following code:
Declare the model method as follows:
public class Models.employees
{
    public string firstName { get; set; }
    public string lastName { get; set; }
}

public class Models.RootObject
{
    public List<employees> employees { get; set; }
}

Controller:
[HttpPost]
public DataSet SaveDetails([FromBody]RootObject Person)
{
    //save opertion.
}

Here comes the expected Result:

A: try like this:
$.ajax(
    {
        url  : "api/Test/SaveDetails",
        type : "POST",
        contentType : 'application/json',
        data : {
                    "obj":
                    [
                        { "firstName": "John", "lastName": "Doe" },
                        { "firstName": "Anna", "lastName": "Smith" },
                        { "firstName": "Peter", "lastName": "Jones" }
                    ]
                },
        success: function (data) {alert("success");},
        error: function () {alert("Error");}
    })

Controller:
[HttpPost]
public DataSet SaveDetails([FromBody]Models.Person[] obj)
{
    //save opertion.
}


text:
Q: Can some one be a bygone? I said 'you are a bygone' to somebody older then me in reference to him not understanding how attending a coding boot camp can train people to become full stack engineers and get a career at a legitimate technology company. Did I use the word right?

A: I would say 'no', "You are from a bygone era." would be fine, but it's not a word I would use applied to people. Well, not living people.


text:
Q: Tile-based collision; Corner collision problems I have implemented a simple tile-based collision system in my top-down game, but I am having problems with moving across corners. Currently, my programs takes the player's center point and works out a tile on a 20px square grid (the alternating grey cbackground). It checks the up, down, left and right tiles for collisions, and if it finds one, it moves onto the next stage.
The next stage is to check where the player is within the tile. For this, I have a function called getCenterDistanceFromCurrentTile() (creative name, I know). This returns a Vector2i (x and y) of the distance from the center point of the tile, to the center point of the player. I then use this in the following ways;

*

*If there is a wall tile to the left, and the player's x distance < 0 (the player is to the left of the current tile's centerpoint), the player is moved to the x of the tile next to the wall.

*If there is a wall to the right, and the player's x distance is > 0 (right of the current tile's centerpoint), the player is moved to the x of the tile next to the wall.

*This continues for the Y axis in the same way.

My problem is with diagonal. I do not check diagonal collisions currently, but it appears I will have to. I have already made an attempt to implement it, but the player jumps around when they hit a corner. I was using the above methods of player x < 0 and player y < 0 together, which didn't work out. I have made some images to better explain my problem.

This image demonstrates my collision system working fine, with a collision to the left (shown by the blue tile), and the pink tiles being checked, but no collision found. The green tile shows the player's current tile, and the red square shows the player's current location.

This image clearly shows the problem I have. None of the pink tiles have collided with anything, therefore the player's x and y do not need to be checked.
How should I check for corner collisions in my game?
My current collision checking code;
public boolean isWall(Vector2i loc)
{
    return this.isWall(loc.x, loc.y);
}

public boolean isWall(int x, int y)
{
    if (x < 0) return true;
    if (y < 0) return true;
    if (y > map[0].length-1) return true;
    if (x > map.length-1) return true;
    return map[x][y];
}

public void phys(Player plr) {
    Vector2i playerTile = plr.getTile();
    // Left
    if (isWall(playerTile.x-1, playerTile.y))
    {
        Vector2i distanceFromTile = plr.getCenterDistanceFromCurrentTile(true);
        if (distanceFromTile.x < 0)
        {
            plr.setX(playerTile.x*BLOCK_SIZE);
        }
    }
    // Right
    if (isWall(playerTile.x+1, playerTile.y))
    {
        Vector2i distanceFromTile = plr.getCenterDistanceFromCurrentTile(true);
        if (distanceFromTile.x > 0)
        {
            plr.setX(playerTile.x*BLOCK_SIZE);
        }
    }
    // Up
    if (isWall(playerTile.x, playerTile.y-1))
    {
        Vector2i distanceFromTile = plr.getCenterDistanceFromCurrentTile(true);
        if (distanceFromTile.y < 0)
        {
            plr.setY(playerTile.y*BLOCK_SIZE);
        }
    }
    // Down
    if (isWall(playerTile.x, playerTile.y+1))
    {
        Vector2i distanceFromTile = plr.getCenterDistanceFromCurrentTile(true);
        if (distanceFromTile.y > 0)
        {
            plr.setY(playerTile.y*BLOCK_SIZE);
        }
    }
}

A: Your phys method could return boolean depending on whether the player is colliding with any of the walls. You could then use the result of this function to decide whether to move back to the previous location in space you were before you moved, or if you did not collide, to continue on.
This would require you to check all of the adjacent walls around the player. This would introduce a much cleaner way of iterating through the collision checks in the phys method.
Such an improvement would look like:
public boolean phys(Player plr)
{
    java.awt.Rectangle playerBounds = new java.awt.Rectangle(plr.x, plr.y, BLOCK_SIZE, BLOCK_SIZE);

    for (int y = 0; y < 3; y++)
    {
        for (int x = 0; x < 3; x++)
        {
            // Skip the tile the player is on assuming that he is not on a wall already
            if (x == 1 && y == 1) continue;

            java.awt.Rectangle bounds = new java.awt.Rectangle(/*tile at (x, y) xpos*/, /*tile at (x, y) ypos*/, BLOCK_SIZE, BLOCK_SIZE);

            if (bounds.intersects(playerBounds))
            {
                return true;
            }
        }
    }

    // Did not collide
    return false;
}


text:
Q: Correct statement of Fermat's Last Theorem I'm looking at the wikipedia page on Fermat's Last Theorem
In the statement it requires $a,b,c$ to be positive integers.  Is that correct?  I always took it to be no solutions in non-zero integers.  But this wiki page makes a big deal out of the bases being positive.  Has some counter-example turned up using negative integers that I'm missing?  Otherwise, I think we should fix the wiki page.

A: We are considering the equation
$$
a^n + b^n = c^n.
$$
Clearly if $n$ is even, then negatives just go away, so let's say that $n$ is odd.
You have some cases. One case is where $a$ and $c$ are positive, but $b$ is negative. Then the equation is equivalent to $a^n = (-b)^n + c^n$. So this case isn't interesting. You also have the case where $a$ and $b$ are positive and $c$ is negative. But there clearly is not such solution. If all are negative we also don't get anything new.
Anyway, if you continue considering the different cases you will realize that the important case is where $a$, $b$, and $c$ are all positive.
As @quid says above, if you find a solution in the non-zero integers, then you will have a solution in the natural numbers.

A: Suppose there is a solution in non-zero integers. If $n$ is even this immediately yields a soltution in positive integers.
So suppose $n$ is odd. If all three are negative, we clearly also get a positve solution. So assume one is negative two possitive (two negative, one positive can be reduced to this multipliying by $-1$). Clearly it cannot be $c$ that is negative, so assume it is $a$ but then we get  $ b^n =c^n  -a^n = c^n + (-a)^n$ a positive solution.
In brief, insisting on positve is irrelevant, there are no nono-zero solutions either.

A: The person who had the best possible reason to think about the presentation of the conjecture is Andrew Wiles.  In his paper on Fermat's Last Theorem, the formulation is symmetrical and allows rational solutions:

if $u^p + v^p + w^p = 0$ with $u,v,w$ rational and $p \geq 3$, then $uvw=0$.

It's interesting that he also chose to not use the traditional letters $x,y,z$ and $n$ for the variables in the problem.  His paper "buries the lede" by not giving the elementary form of FLT until the sixth page, and stays as far away as possible from the archetypal Diophantine form of FLT other than to mention he has proved it, and to quote Fermat's formulation in Latin below the dedication.

A: The formulations are equivalent. This is clear when $n$ is even (because then $x^n=(-x)^n$), so assume $n$ is odd. I will prove that if FLT has no positive solutions, it will have no non-zero solutions. We have few cases:

*

*$a,b,c>0$ - we know this doesn't have solutions.

*$a,b,c<0$ - if these were a solution, we would have $a^n+b^n=c^n$ and then by multiplying by $(-1)^n$ we would have $(-a)^n+(-b)^n=(-c)^n$ with $-a,-b,-c>0$.

*$a,b<0, c>0$ - this is impossible, as then $a^n+b^n<0<c^n$

*$a,b>0, c<0$ - same as above.

*$a>0,b<0,c>0$ - if we have $a^n+b^n=c^n$, then $c^n+(-b)^n=a^n$.
Rest of the cases goes similarly, which I will leave for you.


text: Q: How to print Google Visualization API Line chart in Razor/MVC3 using javascript? I could able to display the chart using google api, but unable to print using javascript. The chart I am printing is using the  tags with id="chart_div". Please help.


text:
Q: Listing number of obervations by location Need help here. I am trying to create a new column that will list the number of restaurants with in 200 meters of a restaurant using latitude and longitude. I couldn't find anything on stackoverflow, and I am no R ninja. Any help would be appreciated!
head()
 business_id                        restaurantType                                               full_address open       city
1 --5jkZ3-nUPZxUvtcbr8Uw                Greek             1336 N Scottsdale Rd\nScottsdale, AZ 85257    1 Scottsdale
2 --BlvDO_RG2yElKu9XA1_g           Sushi Bars 14870 N Northsight Blvd\nSte 103\nScottsdale, AZ 85260    1 Scottsdale
3 -_Ke8q969OAwEE_-U0qUjw Beer, Wine & Spirits                   18555 N 59th Ave\nGlendale, AZ 85308    0   Glendale
4 -_npP9XdyzILAjtFfX8UAQ           Vietnamese          6025 N 27th Avenue\nSte 24\nPhoenix, AZ 85073    1    Phoenix
5 -2xCV0XGD9NxfWaVwA1-DQ                Pizza                      9008 N 99th Ave\nPeoria, AZ 85345    1     Peoria
6 -3WVw1TNQbPBzaKCaQQ1AQ              Chinese                     302 E Flower St\nPhoenix, AZ 85012    1    Phoenix
review_count                       name longitude state stars latitude     type categories1          categories2
 1           11 George's Gyros Greek Grill -111.9269    AZ   4.5 33.46337 business       Greek                 <NA>
 2           37               Asian Island -111.8983    AZ   4.0 33.62146 business  Sushi Bars             Hawaiian
 3            6    Jug 'n Barrel Wine Shop -112.1863    AZ   4.5 33.65387 business        <NA> Beer, Wine & Spirits
 4           15          Thao's Sandwiches -112.0739    AZ   3.0 33.44990 business  Vietnamese           Sandwiches
 5            4          Nino's Pizzeria 2 -112.2766    AZ   4.0 33.56626     business       Pizza                 <NA>
 6          145                China Chili -112.0692    AZ   3.5 33.48585 business     Chinese                 <NA>

   avgStar duration delta
1 3.694030      381     0
2 3.661017      690     0
3 3.555556      604     1
4 3.577778     1916     0
5 3.482036      226     0
6 3.535928     2190     0

str()
'data.frame':   2833 obs. of  28 variables:
 $ business_id   : Factor w/ 2833 levels "--5jkZ3-nUPZxUvtcbr8Uw",..: 1 2 3 4 5 6 7 8 9 10 ...
 $ restaurantType: Factor w/ 118 levels "Afghan","African",..: 60 106 15 117 89 31 17 7 84 31 ...
 $ full_address  : Factor w/ 2586 levels "1 E Jackson St\nPhoenix, AZ 85004",..: 274 371 642 1825 2368 1102 1000 1143 2169 1669 ...
 $ open          : int  1 1 0 1 1 1 1 1 1 1 ...
 $ city          : Factor w/ 44 levels "Ahwatukee","Anthem",..: 34 34 19 31 30 31 34 4 18 31 ...
 $ review_count  : int  11 37 6 15 4 145 255 35 7 7 ...
 $ name          : Factor w/ 2652 levels "#1 Brother's Pizza",..: 885 127 1167 2318 1601 453 591 697 1492 1319 ...
 $ longitude     : num  -112 -112 -112 -112 -112 ...
 $ state         : Factor w/ 2 levels "AZ","SC": 1 1 1 1 1 1 1 1 1 1 ...
 $ stars         : num  4.5 4 4.5 3 4 3.5 4.5 4 2.5 4.5 ...
 $ latitude      : num  33.5 33.6 33.7 33.4 33.6 ...
 $ type          : Factor w/ 1 level "business": 1 1 1 1 1 1 1 1 1 1 ...
 $ categories1   : Factor w/ 103 levels "Afghan","African",..: 50 93 NA 102 78 26 14 7 73 26 ...
 $ Freq          : int  66 58 8 44 166 166 98 35 45 166 ...
 $ avgRev        : num  31.3 68.6 34.3 63.2 30.8 ...
 $ avgStar       : num  3.69 3.66 3.56 3.58 3.48 ...
 $ duration      : int  381 690 604 1916 226 2190 1968 1338 1606 56 ...

A: One approach would be to compute the distance matrix, and then to figure out the ones that are sufficiently close (here I demonstrate being within 20 kilometers so the numbers aren't all 0):
# Load the fields library
library(fields)

# Create a simple data frame to demonstrate (each row is a restaurant). The rdist.earth function
# we're about to call takes as input something where the first column is longitude and the second
# column is latitude.
df = data.frame(longitude=c(-111.9269, -111.8983, -112.1863, -112.0739, -112.2766, -112.0692),
                latitude=c(33.46337, 33.62146, 33.65387, 33.44990, 33.56626, 33.48585))

# Let's compute the distance between each restaurant.
distances = rdist.earth(df, miles=F)
distances

#          [,1]     [,2]     [,3]         [,4]     [,5]         [,6]
# [1,]  0.00000 17.79813 32.07533 1.373515e+01 34.41932 1.344867e+01
# [2,] 17.79813  0.00000 26.93558 2.510519e+01 35.61413 2.189270e+01
# [3,] 32.07533 26.93558  0.00000 2.498676e+01 12.85352 2.162964e+01
# [4,] 13.73515 25.10519 24.98676 1.344145e-04 22.84310 4.025824e+00
# [5,] 34.41932 35.61413 12.85352 2.284310e+01  0.00000 2.122719e+01
# [6,] 13.44867 21.89270 21.62964 4.025824e+00 21.22719 9.504539e-05

# Compute the number of restaurants within 20 kilometers of the restaurant in each row.
df$num.close = colSums(distances <= 20) - 1
df$num.close
# [1] 3 1 1 2 1 2

A: Base R and untested code but you should get the idea.
I'm basically testing how many rows fall within the circle equation x2 + y2 <= R for each restaurant, except for that restaurant itself, and updating that as the value in the column. Note that the radius in my equation is 200 but it will be different because your x,y is in latitude, longitude and you will have to scale the radius of 200 metres to 2pi radians / circumference of earth or 360 degree / circumference of earth.
df <- data.frame(
  latitude = runif(n=10,min=0,max=1000),
  longitude = runif(n=10,min=0,max=1000)
  )

for (i in seq(nrow(df)))
{
  # circle's centre
  xcentre <- df[i,'latitude']
  ycentre <- df[i,'longitude']

  # checking how many restaurants lie within 200 m of the above centre, noofcloserest column will contain this value
  df[i,'noofcloserest'] <- sum(
    (df[,'latitude'] - xcentre)^2 +
      (df[,'longitude'] - ycentre)^2
    <= 200^2
  ) - 1

  # logging part for deeper analysis
  cat(i,': ')
  # this prints the true/false vector for which row is within the radius, and which row isn't
  cat((df[,'latitude'] - xcentre)^2 +
    (df[,'longitude'] - ycentre)^2
  <= 200^2)

  cat('\n')

}

Output -
1 : TRUE FALSE FALSE TRUE FALSE TRUE FALSE FALSE FALSE FALSE
2 : FALSE TRUE FALSE FALSE FALSE FALSE FALSE FALSE FALSE FALSE
3 : FALSE FALSE TRUE FALSE TRUE FALSE FALSE FALSE FALSE FALSE
4 : TRUE FALSE FALSE TRUE FALSE TRUE FALSE FALSE FALSE FALSE
5 : FALSE FALSE TRUE FALSE TRUE FALSE FALSE TRUE FALSE FALSE
6 : TRUE FALSE FALSE TRUE FALSE TRUE FALSE FALSE FALSE FALSE
7 : FALSE FALSE FALSE FALSE FALSE FALSE TRUE FALSE FALSE TRUE
8 : FALSE FALSE FALSE FALSE TRUE FALSE FALSE TRUE FALSE FALSE
9 : FALSE FALSE FALSE FALSE FALSE FALSE FALSE FALSE TRUE FALSE
10 : FALSE FALSE FALSE FALSE FALSE FALSE TRUE FALSE FALSE TRUE
> df
    latitude longitude noofcloserest
1  189.38878 270.25004             2
2  402.36853 879.26657             0
3  747.46417 581.66627             1
4  291.64303 157.75450             2
5  830.10699 736.19586             2
6  299.06803 157.76147             2
7  725.68360  58.53049             1
8  893.31904 772.46217             1
9   45.47875 701.82201             0
10 645.44772 226.95042             1

What that output means is that for the coordinates at row 1, three rows are within 200 m. Row 1 itself, and rows 4 and 6.


text:
Q: How to construct enum with custom type using JavaPoet Is it possible to generate the following enum class using JavaPoet?
public enum EnumName {

  import com.sth.sth.SomeClass1;
  import com.sth.sth.SomeClass2;

  ITEM1(new CustomType<SomeClass1>("string1", "string 2", SomeClass1.class)),
  ITEM2(new CustomType<SomeClass2>("string1", "string 2", SomeClass2.class));

  EnumName(CustomType customType) {
    this.customType = customType;
  }

  private final CustomType customType;

  public CustomType getCustomType() {
    return customType;
  }
}

i can create everything but i have huge struggle with initialisation block within the ITEMs.
My current code is
TypeSpec.Builder typeSpecBuilder = TypeSpec.enumBuilder("EnumName")
                .addModifiers(PUBLIC)
                .addField(TypeVariableName.get("CustomType"), "customType", PRIVATE, FINAL)
                .addMethod(MethodSpec.constructorBuilder()
                                     .addParameter(TypeVariableName.get("CustomType"), "customType")
                                     .addStatement("this.$N = $N", "customType", "customType")
                                     .build())
                .addMethod(MethodSpec.methodBuilder("getCustomType")
                                     .addModifiers(PUBLIC)
                                     .addStatement("return customType")
                                     .returns(TypeVariableName.get("CustomType"))
                                     .build());
for (Model model : models) {
    typeSpecBuilder.addEnumConstant(prepareName(model), HERE I DO NOT KNOW HOW TO BUILD TypeSpec that would create what i need);
}

i was able to create this
public enum EnumName {

  ITEM1("ITEM1"){
    @Override
    public CustomType getCustomType(){
      return new CustomType<SomeClass1>("string1", "string 2", SomeClass1.class));
    }
  },
  ITEM2("ITEM2"){
    @Override
    public CustomType getCustomType(){
      return new CustomType<SomeClass2>("string1", "string 2", SomeClass2.class));
    }
 };

  EnumName(customTypeName customTypeName) {
    this.customTypeName = customTypeName;
  }

  private final String customTypeName;

  public String getCustomTypeName() {
    return customTypeName;
  }

by adjusting for cycle like so:
for (Model model : models) {
    typeSpecBuilder.addEnumConstant(prepareName(model), TypeSpec.anonymousClassBuilder("$S", prepareName(model))
    .addMethod(MethodSpec.methodBuilder("getCustomType")
    .addAnnotation(Override.class)
    .addModifiers(PUBLIC)
    .addStatement(getInitStatement(model))
    .returns(TypeVariableName.get("CustomType"))
                            .build())
                    .build());
}

This is partially ok but i do not know how to generate imports for those classes.
I prefer first option
ITEM1(new CustomType<SomeClass1>("string1", "string 2", SomeClass1.class))

but if it cannot be done can someone suggest how to generate imports for the second example with adjusted for cycle?
Thank you very much for any suggestion.

A: Ok found solution if anyone will be interested in future.
String fullyQualifiedClassName = getClassName();
if (fullyQualifiedClassName == null) {
  fullyQualifiedClassName = "Object";  //important if class was not found we need set to object -> otherwise there will not be imports for some reason
}
TypeName typeName = ClassName.bestGuess(fullyQualifiedClassName);
for (Model model : models) {
    typeSpecBuilder.addEnumConstant(prepareName(model), TypeSpec.anonymousClassBuilder("new CustomType<$T>($S, $S, $T.class)", typeName, string1, string2, typeName));
}


text:
Q: Is it bad form to put an exception class in the same file as your main class I'm writing a very simple program with only one class. I also want to derive my own exception but I don't want to have to use a new file. Is this okay or is it bad coding to have multiple not exactly related classes in one file?

A: It's okay for small projects, but can quickly turn into a maintenance headache for anything bigger then that.
Categorizing classes inside both files and namespaces helps with organization, is more intuitive to where you can find what you're looking for, and is much much easier to keep track of changes (in version control).
There's also the matter of dependencies, which is probably the most important one - what if you want to use that exception somewhere else? You can't include the implementation file, and even if you keep it an a header shared with other unrelated classes, you'd be polluting the new translation unit with unneeded symbols.

A: I think the answer, like many things, is that it depends.  In this case, the question would be how tightly coupled the exception is to the class.  If your class is called FooBarBaz and your exception is called FooBarBazException the it seems unlikely that anyone would want to use it elsewhere and I think it's alright to package it with the class.  (In fact, you might argue that it should be a nested class of FooBarBaz.)
That said, when I write exceptions I try to tie them to causes rather than specific classes.  For example, if I'm writing a compression library and I have support for several different algorithms, I may write a single DataCorruptionException class to convey detection of corruption.  Then I can use the exception message to provide more detailed information, such as what class/function the exception came from.


text:
Q: Awk access to dictionary in gsub I have the next code and I want to access the position "\1" which matches in the text like (([0-9]+)) in the dictionary d that I create in the BEGIN block.
The problem is that in gensub, d[["\1"]] prints this literally, instead of the dictionary word.
How could I achieve it?
awk 'BEGIN {
  while (getline < "dictionary")
     d["(("i++"))"]=$0
}
{
for (i=1; i<=NF; i++)
  $i=tolower($i)
}
{
print gensub(/(\(\([0-9]+\)\))/, d["\\1"], "g")
}' fileToReplace.log

Example of fileToReplace.log:
|||

I want to go to d'((2)) from ((1)

I want to go

To d'(1))

From (4)

|||

Example of dictionary:
UK
Dublin
Madrid
Ireland

And the expected output is:
|||

I want to go to d'Dublin from UK

I want to go

To d'UK

From Ireland

|||

Basically what I need is to match the number inside any combination of parens and replace this combination (all the parens and the number) with its corresponding position in the dictionary

A: The d["\\1"] is evaluated before gensub() is even called and so before "\\1" has any meaning other than that literal string, certainly not a backreference expansion. Look:
$ echo 'aBc' | awk '{d["B"]="X"; sub(/B/,d["&"])}1'
ac

$ echo 'aBc' | awk '{d["&"]="X"; sub(/B/,d["&"])}1'
aXc

You want something like this:
$ cat tst.awk
NR==FNR { d[NR]=$0; next }
{
    head = ""
    tail = tolower($0)
    while ( match(tail,/\(+[0-9]+\)+/) ) {
        trgt = substr(tail,RSTART,RLENGTH)
        gsub(/[()]/,"",trgt)
        head = head substr(tail,1,RSTART-1) d[trgt]
        tail = substr(tail,RSTART+RLENGTH)
    }
    print head tail
}

$ awk -f tst.awk dictionary fileToReplace.log
|||

i want to go to d'Dublin from UK

i want to go

to d'UK

from Ireland

|||