Symfony2, manually assign table id value

Question: I'm working with symfony2, I have a table and I want to manually assign the id.
In the documentation of doctrine I've found this:
Identifier Generation Strategies
"NONE: Tells Doctrine that the identifiers are assigned (and thus generated)
 by your code. The assignment must take place before a new entity is passed to
 EntityManager#persist.
 NONE is the same as leaving off the @GeneratedValue entirely."

Pay attention to this: "the assignment must take place before a new entity is passed to En.."
How do I achieve that?
I'm doing this:
$empleado->setId("989865446");

but it says:
Entity of type Entity\Empleado is missing an assigned ID. The identifier
generation strategy for this entity requires the ID field to be populated before
EntityManager#persist() is called. If you want automatically generated
identifiers instead you need to adjust the metadata mapping accordingly.

EDIT:
 /**
 * @var integer $id
 * @ORM\Column(name="id", type="integer", nullable=false)
 * @ORM\Id
 */
private $id;

and
public function setId($id)
{
    $this->id = $id;
}

Comment: Can you show us the relevant code surrounding `$empleado->setId()`?
Comment: How did you implement `setId()` ?
Comment: And needless to say (but I'll say it anyways) make sure your id property is called id.
Comment: I edited the post, so there is the code. Hope you help me.
Comment: Do you use some third party bundles? Maybe one of these calls `persist`. Or some service?
Comment: I'm just using doctrine, and no, there are not more third party bundles. What I really want to know is what does it mean "The assignment must take place before a new entity is passed to
 EntityManager#persist." because that's how I would solve the problem.
Answer: The code you posted is correct, so the error must have to do with how you're constructing the object and when persist() is called.
There's a similar question here:
Set value for the primay key with strategy set to NONE
Are you running the latest versions of Symfony 2/Doctrine 2?
Try making it a required constructor parameter as suggested in the answer above - that should make it impossible for persist() to be called before setting the ID. The error message means just what it says - you have to assign the ID first, only then call persist.
You are creating the object normally, correct? Your code should look like this (here I'm showing how it would work with the ID required by the constructor, but it should work with the setId() approach too):
$empleado = new Entity\Empleado("989865446");
//set other properties
$em->persist($empleado);

Comment: I do need the @GeneratedValue, but want to load fixtures with custom ids. I used this solution: http://www.ens.ro/2012/07/03/symfony2-doctrine-force-entity-id-on-persist/
Comment: I had exactly the same problem as @afilina and I used the almost the same solution, just the constant seems to be on a different class now (in newer versions of doctrine): `$metadata = $em->getClassMetaData(get_class($entity));
        $metadata->setIdGeneratorType(ClassMetadataInfo::GENERATOR_TYPE_NONE); //use Doctrine\Common\Persistence\Mapping\ClassMetadata;`
Comment: I tried both approaches, with setId and constructor. The id is set correctly, but then persists with the next auto-increment.
Comment: @afilina Did you make sure that your ID property does not have a `@GeneratedValue` annotation?


How to distribute Python package with Numba as optional dependency

Question: Given a numba-decorated code,
from numba import jit

@jit(nopython=True)
def f():
    ...

, how does one distribute this as a package with Numba as an optional dependency? For example, I want to install my package via pip install mypackage[jit] that includes numba and removing the extra tag excludes numba.
A bad answer is one that requires user to install Numba and, for example, set NUMBA_DISABLE_JIT=1.
Answer: Create a dummy decorator:
try:
    from numba import jit
except ImportError:
    def jit(*args, **kwargs):
        return lambda f: f

@jit(nopython=True)
def f():
    ...

Answer: A solution, albeit not pretty...
USE_NUMBA = True
try:
    from numba import jit
except ImportError:
    USE_NUMBA = False

def f():
    ...

if USE_NUMBA:
    f = jit(nopython=True)(f)


Why can $R^2$ be negative in linear regression -- interview question

Question: I was asked an $R^2$ question during an interview, and I felt like I was right then, and still feel like I'm right now. Essentially the interviewer asked me if it is possible for $R^2$ to be negative for linear regression.
I said that if you're using OLS, then it is not possible because the formal definition of $R^2$ is
$$
R^2 = 1 - \frac{SS_{res}}{SS_{tot}}
$$
where $SS_{tot} = \sum_i^n (y_i - \bar{y})^2$ and  $SS_{res} = \sum_i^n (y_i - \hat{y_i})^2$.
In order for $R^2$ to be negative, the second term must be greater than 1. This would imply that $SS_{res} > SS_{tot}$, which would imply that the predictive model fits worse than if you fit a straight line through the mean of the observed $y$.
I told the interviewer that it is not possible for $R^2$ to be 1 because if the horizontal line is indeed the line of best fit, then OLS fill produce that line unless we're dealing with an ill-conditioned or singular system.
He claimed that this isn't correct and that $R^2$ can still be negative, and that I could "see it easily in the case where there is no intercept." (note that all of the discussion so far was about the case WITH an intercept, which I confirmed at the beginning by asking if there are any constraints about the best line passing through the origin, which he stated "no")
I can't see this at all. I stood by my answer, and then mentioned that maybe if you used some other linear regression method, perhaps you can get a negative $R^2$.
Is there any way for $R^2$ to be negative using OLS with or without intercept? Edit: I do understand that you can get a negative $R^2$ in the case without an intercept.
Comment: The $R^2$ is nowadays often seen as ratio of model variance and data variance. But it is actually a correlation between the model and data. In *that* view the $R^2$ is necessarily between 0 and 1. As a ratio of variances, and only as 1 minus the ratio of error:data, then you can easily get negative values due to all sorts of things that might get the model to be worse than just fitting with the mean (e.g. when applying shrinking then you might include an intercept but still get worse than the mean).
Comment: What sort of job has this as an interview question?
Comment: Sorry to say, your interviewer is a moron - while $R^2$ can be negative if you force the intercept to $0$, there is never any reason to do so. If you only care about of out sample predictions, it will almost always be worse than including an intercept. If you care about parameter inference, it will always you lead to biased and inconsistent estimate for both model parameters (i.e. the estimated $\beta$) and model variance. If your explanation of the situation is true, then you very likely dodged a bullet by not getting hired.
Comment: https://stats.stackexchange.com/questions/12900/when-is-r-squared-negative
Comment: @dwolfeu Yeah I saw that post, but it doesn't necessarily answer my specific questions here.
Comment: @COOLSerdash No. The comment above linked to the same post, and I reponded to it.
Comment: @SextusEmpiricus This is for a quantitative researcher/developer role at a hedge fund.
Comment: @Repmat I think there may have been a language barrier issue, but we weren't talking about about OOS, and it was strictly on the training samples. He passed me for this interview though (it was just a phone screen, so there's more, and I hope the other interviewers aren't this way), which kind of surprised me b/c he insisted that I was wrong, but I think I answered all other questions correctly.

Isn't $R^2$ typically only evaluating the inference and so typically only computed for training samples, and not for test data/OOS data (I'm a bit iffy on the difference between OOS vs. test data).
Answer: The interviewer is right. Sorry.
set.seed(2020)
x <- seq(0, 1, 0.001)
err <- rnorm(length(x))
y <- 99 - 30*x + err
L <- lm(y~0+x) # "0" forces the intercept to be zero
plot(x, y, ylim=c(0, max(y)))
abline(a=0, b= summary(L)$coef[1], col='red')
abline(h=mean(y), col='black')
SSRes <- sum(resid(L)^2)
SSTot <- sum((y - mean(y))^2)
R2 <- 1 - SSRes/SSTot
R2

I get $R^2 = -31.22529$. This makes sense when you look at the plot the code produces.

The red line is the regression line. The black line is the "naive" line where you always guess the mean of $y$, regardless of the $x$.
The $R^2<0$ makes sense when you consider what $R^2$ does. $R^2$ measures how much better the regression model is at guessing the conditional mean than always guessing the pooled mean. Looking at the graph you're better off guessing the mean of the pooled values of $y$ than you are using the regression line.
EDIT
There is an argument to be made that the "SSTot" to which you should compare an intercept-free model is just the sum of squares of $y$ (so $\sum (y_i-0)^2$), not $\sum (y_i - \bar{y})^2$. However, $R^2_{ish} = 1- \frac{\sum(y_i - \hat{y}_i)^2}{\sum y_i^2}$ is quite different from the usual $R^2$ and (I think) loses the usual connection to amount of variance explained. If this $R^2_{ish}$ is used, however, when the intercept is excluded, $R^2_{ish} \ge 0$.
Comment: Perhaps he meant some kind of regularized regression or out-of-sample $R^2$.
Comment: Pretty much everything you know about regression (me too) is about regression with an intercept. The sentiment on here is that the proper time to exclude the intercept, though, is pretty much never.
Comment: Also consider that the R^2 is a measure for *any* trendline. It need not be estimated from regression, estimated at all, or if it is a regression, an R^2 reported on the same dataset.  I hadn't considered this, very interesting question.
Comment: @AdamO That's an interesting thought. The obvious line of thinking is that $\hat{\beta} = \hat{\beta}_{ols}$, but $\hat{\beta}_{silly} = (0, 118.391)$ no matter the data, is an estimate, and there is some $R^2$ value for that estimate. In my example, that results in an awful $R^2$.
Comment: Sorry, I mispoke in my original post. So I do see why the case without the intercept would have a negative $R^2$. But he insisted that this could also occur for the case WITH an intercept, and then proceeded to tell me that I could "see this by considering the case without an intercept," which doesn't make sense to me because the case without an intercept is an entirely different regression model, and I don't see how looking at that case would show me how $R^2$ can be $<0$ for the case WITH an intercept.
Comment: Just edited the OP to make this part clearer.
Comment: I'm curious about your plot. In the case where the intercept IS included, I know that the regression line passes through $\bar{x}, \bar{y}$, i.e., $\hat{y} = \bar{y} = \hat{\beta}_1 \bar{x} + \hat{\beta}_0$. For your case without the intercept it seems that it doesn't. I can't really read $R$, but I assume the mean of your observed values have $\bar{x} = 0.5$?
Comment: My $x$ is $0, 0.001, 0.002,...,0.999,1$, so $\bar{x}=0.5$.
Comment: So it seems the regression model without an intercept doesn't pass through $(\bar{x}, \bar{y})$?
Comment: Apparently not. The red and black lines intersect around $0.7$, not $0.5$.
Comment: That's interesting. I've never thought about this case before. I might try to prove why it doesn't necessarily pass through the centers mathematically.
Answer: It looks like your interview was correct.
In the case that you include an intercept it is not possible.
The easiest way to see this is to take the projection view of linear regression.
$\hat{y} = X\hat{\beta} = X(X^TX)^{-1}X^TY = P_XY$
Where $P_X$ is a orthogonal projection matrix. It projects vectors into the subspace spanned by linear combinations of $X$. You can think of this as shining a light on the vector into the linear subspace spanned by X. It maps $Y$ to the closest possible part of the subspace.
We can also define the projection onto a subspace spanned by an intercept, denoted $P_\iota$, where $\iota$ is a vector of ones.
It turns out that $P_\iota Y = \bar{y}$, a $n \times 1$ vector with the mean as each value. In other words, the best possible linear approximation to $Y$ using only combinations of constants would be the mean. That makes sense and you may have seen related results in a stats class before.
If $X$ includes an intercept then the linear subspace spanned by $X$ is a superset of the linear subspace spanned by an intercept. What this means is that since $P_X$ finds the closest approximation in the subspace and it contains the intercept subspace, then it has to be at least as close to $Y$ as the best approximation in the span of $\iota$. In other words $|Y - \hat{y}|  = |Y - P_XY|  \leq |Y - P_\iota Y| = |Y - \bar{y}|$ if $X$ contains the intercept (and thus the squares must also follow this inequality).
Now if we do not include an intercept, this is no longer true, because the linear span of $X$ is no longer a superset of the intercept linear space. It is thus no longer guaranteed that our prediction is at least as good as the mean.
Consider the example where $X$ is a single variable with mean 0, finite variance and is independent of $Y$, and $Y$ has some arbitrary mean $E[Y] \neq 0$ (but exists).
$\hat{\beta} = (X^TX)^{-1}X^TY \overset{p}{\to} \frac{ E[XY] }{ E[X^2] } = \frac{E[X]E[Y]}{E[X^2]} = 0$
As n gets large, the coefficient becomes arbitrarily close to zero. This means that $\hat{y} \overset{p}{\to} 0$
Using the centered $\mathcal{R}^2$ formula we get
\begin{align}
1 - \frac{\sum_{i=1}^n (y_i - \hat{y})^2}{\sum_{i=1}^n(y_i -\bar{y})^2} &= 1 - \frac{\sum_{i=1}^n (y_i - o_p(1))^2}{\sum_{i=1}^n(y_i -\bar{y})^2}\\
&\overset{p}{\to} 1 - \frac{E[Y^2]}{var(Y)}\\
& = 1 - \frac{E[Y^2]}{E[Y^2] - (E[Y])^2} \leq 0
\end{align}
So if $X$ doesn't really explain anything in $Y$, and the mean of $Y$ is far from 0, we can have a really negative $\mathcal{R}^2$
Below is some R code to simulate such a case
set.seed(2020)
n <- 10000
y <- rnorm(n,50,1)
x <- rnorm(n)

mod <- lm(y ~   -1 + x)
yhat <- predict(mod)

R2  <- 1 - sum((y - yhat)^2)/sum((y - mean(y))^2)
R2

$\mathcal{R^2} = -2514.479$
Edit: I agree with Dave that when we don't include an intercept it would be reasonable to argue that the uncentered $\mathcal{R}^2$ is the more natural $\mathcal{R}^2$ measure. The problem with the uncentered version is that it is not invariant to changes in the mean of the regressand (see Davidson and Mackinnon: Econometric Theory and Methods chapter 3 for discussion).
Comment: I mispoke in the OP (see edits), but the interview essentially claimed that $R^2$ can be negative in the case with an intercept. Btw, I like projection and column space perspective. It's relatively more aligned with my background (more numerical linear algebra than stats).
Comment: Yeah in that case, I believe his is wrong.
Comment: since in that case we can write $1 - \frac{SS_{res}}{SS_{tot}}  = 1 - \frac{|(I_n - P_X)Y|^2}{|(I_n - P_{\iota})Y|^2}$, which as we showed the numerator must be at least as small as the denominator in the fraction. Big bummer you had to deal with that. And yes, big fan of the geometric vector space perspective. If this is more your style than traditional stats, you might enjoy more general semi-parametric methods  which can be put into hilbert spaces with this kind of flavour
Comment: Btw, from a linear algebra perspective, do you know why for the case without an intercept, the regression line isn't guaranteed to pass through $(\bar{x} , \bar{y})$? Is it simply because the column space of $X$ is no longer spanned by $1 \in \mathbb{R}^n$? So $\hat{y}$ can't be written as a linear combination of $\bar{X}_{i\in \{1, \ldots, p\}}$? It seems this is along the lines, but I don't think this is sufficient.
Comment: I don't have a proper lin alg intuition here, but this is what I can say and maybe it clicks for you.
Comment: The proof requires that the residuals sum to 0. From an optimization perspective, this comes from the f.o.c of the intercept term. We can write this in matrix notation as $\iota^T(I_n - P_X)Y = \iota^TM_XY = 0$, where $M_X$ is the anhililation or residual making matrix. This implies $\bar{y} = \iota^TY = \iota^T X \hat{\beta} = \bar{x}\hat{\beta}$ (thus on the regression line). We can't guarantee the mean 0 residuals without being able to project out a constant, which.turns out to be $\frac{\iota\iota^TM_{X^\prime}Y}{\iota^TM_{X^\prime}\iota}$, Where $X^\prime$ is all non-intercept variables.
Answer: Using OLS with intercept, the only situation with negative R-squared is the following:

You fit your model on a training set.

You apply the model on a fresh test set, calculate the out-of-sample residuals and from there, derive the out-of-sample R-squared. The latter can be negative.

Here the dummy example in R
n <- 100
df <- data.frame(x=rnorm(n), y=rnorm(n))
train <- df[1:70, ]
test <- df[71:n, ]

# Train on train
fit <- lm(y~x, train)
summary(fit) # Multiple R-squared:  3.832e-06

# Evaluate on test
oos_residuals <- test[, "y"] - predict(fit, test)

oos_residual_ss <- sum(oos_residuals^2)
oos_total_ss <- sum((test[, "y"] - mean(train[, "y"]))^2)

1 - oos_residual_ss / oos_total_ss # -0.001413857


One at a time or all at once?

Question: I'm relearning guitar after several years -- well, several decades -- away. I'm actually finding that not only is it coming back to me easily, but I'm learning more than I ever knew before due to all the amazing resources available on the Internet.
Which gives rise to my question. I'm relearning the rock and roll that I played as a kid, but at the same time I'm studying jazz chords, learning pentatonic scales, practicing blues solo techniques, and on and on. I'm wondering whether it's wise to do these things all at once, or if it's better to spend a few weeks concentrating in one area before moving to the next. So far I feel like I'm progressing in each line of study, but would I learn more efficiently if I specialized?
Answer: I think you may get a range of answers here, but in my experience, getting as much input from different disciplines will benefit you immensely, allowing you to utilise chord changes, licks  and other features that you won't necessarily see in rock and roll.
Many of the top rock guitarists use this cross discipline knowledge extensively - think Eric Johnson, Steve Vai, Ritchie Blackmore, Joe Satriani etc.
Put simply - you will have more tools at your disposal, so will be able to compose or improvise more interesting music.
Comment: Absolutely--the more cross-discipline work, the better; so long as you don't sacrifice quality for quantity!
Answer: When learning (or re-learning!) instruments, the most important thing is not to get bored, so learning different aspects at once enable you will never be short of something to practice. You can practice jazz chords and inversions with improvisation over backing tracks, pentatonics you can solo around with. Give yourself things to do so that the enthusiasm remains!
Comment: Sometimes I think that certain things just need time (not necessarily effort) to gel mentally/physically.  You try something, put it aside for a while, and then, boom, when you come back to it, it seems much easier.  So having many irons in the fire is a way to keep that up.

One at a time or all at once?


Request permissions again after user denies location services?

Question: I track the user's location and ask for permission when my load first loads using this:
locationManager.requestAlwaysAuthorization()
locationManager.startUpdatingLocation()

If the user denies, but later changes their mind by enabling the configuration option in my app, how do I ask again? For example, I have a switch for auto detecting the user's location so when they enable it, I am trying to do this:
@IBAction func gpsChanged(sender: UISwitch) {
    // Request permission for auto geolocation if applicable
    if sender.on {
        locationManager.requestAlwaysAuthorization()
        locationManager.startUpdatingLocation()
    }
}

But this code doesn't seem to do anything. I was hoping it would ask the user again if they want to allow the app to track the user's location. Is this possible?
Answer: The OS will only ever prompt the user once. If they deny permission, that's it. What you can do is direct the user to the Settings for your app by passing UIApplicationOpenSettingsURLString to UIApplication's openURL: method. From there, they can re-enable location services if they wish. That said, you probably shouldn't be too aggressive about bugging them for the permission.
Answer: The permission pop-up only shows once.
So we have to redirect users to Settings after that.
Here comes the code in Swift:
 import CoreLocation

 // ...

 @IBAction func userDidClickButton(_ sender: Any) {

    // initialise a pop up for using later
    let alertController = UIAlertController(title: "TITLE", message: "Please go to Settings and turn on the permissions", preferredStyle: .alert)

    let settingsAction = UIAlertAction(title: "Settings", style: .default) { (_) -> Void in
        guard let settingsUrl = URL(string: UIApplicationOpenSettingsURLString) else {
            return
        }
        if UIApplication.shared.canOpenURL(settingsUrl) {
            UIApplication.shared.open(settingsUrl, completionHandler: { (success) in })
         }
    }
    let cancelAction = UIAlertAction(title: "Cancel", style: .default, handler: nil)

    alertController.addAction(cancelAction)
    alertController.addAction(settingsAction)

    // check the permission status
    switch(CLLocationManager.authorizationStatus()) {
        case .authorizedAlways, .authorizedWhenInUse:
            print("Authorize.")
            // get the user location
        case .notDetermined, .restricted, .denied:
            // redirect the users to settings
            self.present(alertController, animated: true, completion: nil)
    }
}

Comment: A quick note: If the case is `.notDetermined` then we are able to use the CLLocationManager.requestForWhenInUseAuthorization() function (as it can only be used once and `.notDetermined` means that the user has not yet decided on location permission for your app).
Answer: You can have an alternate solution!! You can show your own alert with the better message which can convince your user to allow to receive push notifications for your app. If user allows, then only you show default permission alert for enable push notification otherwise if user disallows, don't show default alert in-fact, you can save corresponding flag in your database or NSUserDefaults and can ask user later on again and again on some events in your app.
Comment: This solution is good but you force the user to click twice if they agree, first your popup and then the apple one. Usually you ask for permission in the beginning of the app, maybe in the first startup, maybe you have a welcome intro or a tutorial and this add an extra step. Usually Apple prefert if you keep 1 or 2 step max.
Answer: You only get one chance. For the user to enable permissions after denying them, they have to go through the Settings app. See Requesting Permission to Use Location Services in CLLocationManager.
Answer: I have created the library that include permission manager for notification which handle the permission alert even after user decline the permission.
https://github.com/CrazyPro007/PermissionManager/tree/master/PermissionManager/PermissionManager
Comment: @TruMan1 Please check again, I have uploaded code with contacts permission
Comment: Can you describe how it works?
Answer: For the Health Kit api. Developers can simply add another permission into the readTypes Set<HKObjectType> and the user will be re-prompted to allow permissions. I'm not entirely sure if this works the same way with location services.


Is there a way to determine fragmentation statistics about a single file on Win2003?

Question: Basically, I don't care about fragmentation on the disk as a whole, I'm just curious about one file in particular...  in my case, a SQL database and transaction log file.  I'm looking for something that will provide very basic statistics - number of fragments, average fragement size, etc.  I'm NOT looking for fragmentation statistics of the SQL data / indexes - I already know how to get that.
Answer: Yes - contig.exe can do this (you want the -a flag)
http://technet.microsoft.com/en-us/sysinternals/bb897428.aspx
Comment: +1 - Good utility, that.
Comment: This month's TechNet mag discusses this utility.


Git merge says files were 'deleted by us' when they were not

Question: I'm new to git and am struggling with it a bit.
I was working on about 5 files and went to push them to my remote repo. I was expecting merge errors, but what came back was deleted by us message for 2 of the 5 files I was working on.
I most certainly did not delete these files, nor change their paths. Would anyone know why this has happened and what I can do about it?
git push ${repo_name} ${current_branch_refspec}
Push branch to remote

git merge ${current_branch_refspec}
Merging feature into testing branch

Comment: Please show a git session which results in this error. You should describe the directory hierarchy of your project and show the exact commands that lead up to this error along with all output along the way. You can replace file names and branch names with dummy names if you want to protect your data.
Comment: "went to push them" - you don't (can't) get merge errors on push. Can you explain exactly what you *did* do, and what happened?
Comment: "deleted by us" means that the files were deleted on the current branch.
Comment: @GregHewgill I'm assuming he must have pulled, but let the OP clarify this.
Comment: @GregHewgill added above
Answer: Add all files back and commit again.
git add .

or
git add -A

Then commit
git commit

If you want to remove files then you can use git rm instead of git add


Why is prettier making my Handlebars HTML double quotes into single quotes?

Question: I have a Vue project with a .prettierc.js file that looks like this
module.exports = {
  semi: false,
  arrowParens: 'always',
  singleQuote: true,
  trailingComma: 'es5',
}

So far this has worked as expected, favoring single quotes in JavaScript and TypeScript portions of the code and favoring double quotes in HTML and .vue component files.
However, I need handlebars for some templated HTML so I added the .hbs file. When I ran my formatting step, Prettier converted all the double quotes to single quotes in the .hbs file. Renaming the file to .html prevents this from happening, but isn't an ideal solution.
How can I get prettier to treat .hbs files like .html files and favor double quotes?
Answer: Prettier doesn't recognize .hbs files by default, so it doesn't make an exception to it's configured quoting rule.
Instead, the overrides config attribute can be used to define rule exceptions based on file name/extension.
module.exports = {
  semi: false,
  arrowParens: 'always',
  singleQuote: true,
  trailingComma: 'es5',

  overrides: [
    {
      files: '*.hbs',
      options: {
        singleQuote: false,
      },
    },
  ],
}


Laravel 5 CSRF on prod server, not dev

Question: I develop locally with Laravel Homestead and then have a remote server I push to for production. On my local copy, everything works with no issues. On the prod, I get a Token Mismatch exception on any route I try, even if I curl a page in the server.
I've been searching around for two days now trying to figure out what could cause this and I've had absolutely no luck. I think it may just be a server configuration issue, but I have no idea what would prevent that from working properly. I just cannot figure this out.
/storage has the proper permissions (777 at the moment), the config files have unique session variables, and my .env is currently using 'file' for the session driver. This happens with 'database' as the driver as well though.
If I do hhvm public/index.php or php public/index.php it works as expected, no CSRF issues.
Comment: we're going to need to see some code..
Comment: It happens with a base install of Laravel 5 as well. Not sure what code would help here exactly.
Comment: Is your session ID changing from pageview to pageview?
Comment: @ceejayoz Yes it was, however it was due to a server configuration error. I submitted an answer explaining.
Answer: After a lot of digging, it turns out the solution was pretty simple. HHVM and Nginx were running under the wrong user. I set them both back to www-data and the problem was resolved.

Laravel 5 CSRF on prod server, not dev


Proving the dimension of the intersection of 2 subspaces

Question: Assume that $U$ and $W$ are distinct subspaces $( U  ≠  W )$ of a four-dimensional vector space $V$ and $\dim(U) = \dim(W) = 3$. Prove that $\dim ( U ∩ W ) = 2$.
Answer: since U not equal to W, the basis for W must have at least one vector linearly independent from U, so $\dim(U + W)$ is at least 4. but they are subspaces of $\mathbb R^4$, so $\dim (U + W)=4$.
Use the fact that $\dim U +\dim W=\dim(U + W)+ \dim(U\cap W)$, i.e.
$6=4+\dim(U\cap W)$
Comment: I rewrote the formulae in your post, and  made a correction ($U\cup W$ is not a vector space, hence doesn't have a dimension. It is its span, i.e. $U+W$ which has a dimension.
Comment: How do you prove the fact?


OpenVZ - Ubuntu 12.04 unable to enter

Question: I've setup an Ubuntu 12.04 on OpenVZ, it's been created and appears to start up fine. When I try to enter the OS it just hangs.
I've ran ps aux with the exec and it returns:
USER       PID %CPU %MEM    VSZ   RSS TTY      STAT START   TIME COMMAND
root         1  0.0  0.2   2980  1436 ?        Ss   Jan31   0:00 init
root      3499  0.0  0.1   2816  1048 ?        Rs   Feb01   0:00 ps aux

Any ideas why I am unable to enter the machine?
Thanks
Comment: Sure. Lone running `/sbin/init` is definitely not enough task set to process your login ateempts.
Answer: Are you sure that you are running on 2.6.32-* kernel? Otherwise if you are on the old 2.6.18 kernel you need to do some modifications for it to work ...
Add "ubuntu-12.04 2.6.32" to /etc/vz/osrelease.conf

OpenVZ - Ubuntu 12.04 unable to enter


Bootstrap Confidence Interval, f-value and p-Value

Question: I am trying to understand the intricacies of Linear Regression (1 predictor, 1 response). I am using Istanbul Stock Exchange dataset (https://www.kaggle.com/uciml/istanbul-stock-exchange) to do the same. I am using the column FTSE as my predictor variable and USD BASED ISE as my response variable.
I am writing my own Python (v 3.5.6) methods for all mathematical computation tasks viz. calculating $\beta$s ($\beta_{0}$ and $\beta_{1}$ in my case), calculating MSE, calculating $R^{2}$ etc. I have successfully calculated $\beta$s and could correctly estimate MSE, $R^{2}$ values.
I am trying to understand Boostrap and use the same to estimate

Confidence intervals for coefficients $\beta_{0}$ and $\beta_{1}$
Calculate t-statistic for $\beta_{0}$ and $\beta_{1}$
Calculate p-value for $\beta_{0}$ and $\beta_{1}$

I am trying to calculate the above mentioned statistics without using any statistical package. I have written a function that takes my input dataset and generates 1,00,000 bootstrap samples out of it. For each of these samples I have obtained $\beta_{0}$ and $\beta_{1}$ values. In a nutshell, I have 1,00,000 $\beta_{0}$ and $\beta_{1}$ values. Using these list of values, how do I calculate statistics mentioned in (1), (2) and (3)
Answer: There are in general multiple ways to calculate bootstrap intervals, see Wikipedia for an overview. The case of bootstrap-based confidence intervals for a linear regression is described in detail here.
For instance, let $\hat{\beta}_{1(1)}, \ldots, \hat{\beta}_{1(b)}$ be your $b=1,000,000$ bootstrap estimates of $\beta_1$.
Then, a $(1-\alpha)$-confidence interval for $\beta_1$ can be defined by the $\alpha/2$ and the $(1-\alpha/2)$ quantiles of your bootstrap estimates $\hat{\beta}_{1(1)}, \ldots, \hat{\beta}_{1(b)}$.
Edit: Provided more details.
Comment: Regarding the p-values, I've seen it described like that before, but other answers tend to point out that quantile-based bootstrapping tends to be supoptimal (see https://stats.stackexchange.com/a/277391/60613)


Spark Scala Dataset Type Hierarchy

Question: Trying to enforce classes that extend W to have a method get that returns a Dataset of a subclass of a WR.
abstract class WR

case class TGWR(
          a: String,
          b: String
        ) extends WR

abstract class W {

  def get[T <: WR](): Dataset[T]

}

class TGW(sparkSession: SparkSession) extends W {

  override def get[TGWR](): Dataset[TGWR] = {
    import sparkSession.implicits._

    Seq(TGWR("dd","dd").toDF().as[TGWR]
  }

}

Compilation error:
Unable to find encoder for type stored in a Dataset.  Primitive types (Int, String, etc) and Product types (case classes) are supported by importing spark.implicits._  Support for serializing other types will be added in future releases.

If I change the get function to following:
  def get(): Dataset[TGWR]

and
  override def get(): Dataset[TGWR] = {...

it compiles - therefore I suspect a problem due to inheritance/type hierarchy.
Answer: Forget my comment, I re-read your question and noticed a simple problem.
Here override def get[TGWR] you are not saying that this class produces instances of TGWR, but you are creating a new type parameter of name TGWR, that will shadow your real type.
I fixed it with the following code:
import org.apache.spark.sql.{SparkSession, Dataset}

abstract class WR extends Product with Serializable

final case class TGWR(a: String, b: String) extends WR

abstract class W[T <: WR] {
  def get(): Dataset[T]
}

final class TGW(spark: SparkSession) extends W[TGWR] {
  override def get(): Dataset[TGWR] = {
    import spark.implicits._
    Seq(TGWR("dd","dd")).toDF().as[TGWR]
  }
}

That you can use right this:
val spark = SparkSession.builder.master("local[*]").getOrCreate()
(new TGW(spark)).get()
// res1: org.apache.spark.sql.Dataset[TGWR] = [a: string, b: string]
res1.show()
// +---+---+
// |  a|  b|
// +---+---+
// | dd| dd|
// +---+---+

Hope this is what you are looking for.
Do not doubt to ask for clarification.

Spark Scala Dataset Type Hierarchy


Consulta com subquery

Question:
Preciso responder a essa pergunta:
4) buscar o nome e endereço dos clientes que locaram todos os filmes da locadora.
Não tenho como testar a query, mas séria algo como isso?
SELECT C.nome, C.endereço from CLIENTES C
WHERE EXISTS (
  SELECT * FROM filmes F
  WHERE EXISTS (
    SELECT * from locaçoes L
    where F.id = L.filme and C.id = L.cliente
  )
)

Comment: A pergunta não está muito clara: você quer listar os dados dos clientes que já locaram absolutamente TODOS os filmes da locadora, ou seja, que não falte nenhum filme para ser alugado? Se for o caso a query teria que ser bem diferente disso.
Answer: Para listar os clientes que já alugaram absolutamente todos os filmes do catálogo da locadora, pode-se usar (dentre outras) a seguinte query:
SELECT C.nome, C.endereço FROM CLIENTES C
WHERE (SELECT COUNT(DISTINCT Filme) FROM Locações WHERE cliente = C.id)
      = (SELECT COUNT(1) FROM Filmes)

O que essa query faz é contar a quantidade de locações, sem considerar filmes alugados mais de uma vez (COUNT(DISTINCT Filme)), e listar apenas os que essa contagem seja igual a quantidade total de filmes da locadora.
Comment: Eu tinha tinha tentado assim, porém esqueci do distinct no count, caso o o mesmo cliente tenha alugado o filme 2 vezes ou mais, grato pela solução.

Consulta com subquery


Geocoding: Efficient way to find the distance between two sets of locations

Question: I have a set of coordinates of the locations of different individuals, and another set of coordinates of different drop off boxes, for their ballots. I'm trying to find the distance between their residence, and the nearest dropbox. I've attached a copy of the code I have to work through that as of now--it was replicated from another stack overflow example. However, it is not too efficient, as the dataset I'm working with is millions of rows, and the code relies on finding all possible combinations of coordinates, and then pulling the least distance. Is there a more efficient way to deal with this?
What I currently have:
# Made-Up Data
library(geosphere)
library(tidyverse)
geo_voters <- data.frame(voter_id = c(12345, 45678, 89011)
                    long=c(-43.17536, -43.17411, -43.36605),
                     lat=c(-22.95414, -22.9302, -23.00133))

geo_dropoff_boxes <- data.frame(long=c(-43.19155, -43.33636, -67.45666),
                      lat=c(-22.90353, -22.87253, -26,78901))

# Code to find the distance between voters, and the dropoff boxes
# Order into a newdf as needed first.
# First, the voters:
voter_addresses <- data.frame(voter_id = as.character(geo_voters$voter_id),
                              lon_address = geo_voters$long,
                              lat_address = geo_voters$lat
                              )
# Second, the polling locations:
polling_address <- data.frame(place_number = 1:nrow(geo_dropoff_boxes),
                       lon_place = geo_dropoff_boxes$long,
                       lat_place = geo_dropoff_boxes$lat
                       )

# Create nested dfs:
voter_nest <- nest(voter_addresses, -voter_id, .key = 'voter_coords')
polling_nest <- nest(polling_address, -place_number, .key = 'polling_coords')

# Combine for combinations:
data_master <- crossing(voter_nest, polling_nest)

# Calculate shortest distance:
shortest_dist <- data_master %>%
  mutate(dist = map2_dbl(voter_coords, polling_coords, distm)) %>%
  group_by(voter_id) %>%
  filter(dist == min(dist)) %>%
  mutate(dist_km = dist/1000,
         voter_id = as.character(voter_id)) %>%
  select(voter_id, dist_km)

Answer: The sf package makes this simple. The st_as_sf() function converts data frame of lat-long values to georeferenced points, and the st_distance() function calculates the distances between them.  When running st_as_sf(), you'll need to specify a coordinate reference system. It looks like you're using latitude and longitude, so I specify crs="epsg:4326", which is the most common latitude/longitude reference.
library( sf )

geo_voters <- data.frame(voter_id = c(12345, 45678, 89011)
                    long=c(-43.17536, -43.17411, -43.36605),
                     lat=c(-22.95414, -22.9302, -23.00133))

geo_dropoff_boxes <- data.frame(long=c(-43.19155, -43.33636, -67.45666),
                      lat=c(-22.90353, -22.87253, -26.78901))

# convert the data to sf features
geo_voters = st_as_sf( geo_voters, coords=c('long', 'lat'), crs="epsg:4326" )
geo_dropoff_boxes = st_as_sf( geo_dropoff_boxes, coords=c('long', 'lat'), crs="epsg:4326" )

# calculate the distances between voters and drop boxes
dist = st_distance( geo_voters, geo_dropoff_boxes )
print(dist)

Now each row represents a voter and each column represents their distance to a drop box (in meters):
Units: [m]
          [,1]     [,2]    [,3]
[1,]  5866.745 18821.87 2482400
[2,]  3461.945 17813.57 2483210
[3,] 20916.618 14641.09 2462186


Como funciona exatamente o canvas.compose() do Lua?

Question:
canvas:compose (x, y, canvas_src)
Faz a composição pixel a pixel entre dois canvas.
O canvas passado como src`é desenhado sobre o canvas em uso (canvas)
na posição passada.
Recebe:

x: [number] Posição x da composição.
y: [number] Posição y da composição.
canvas_src: [canvas] Canvas a ser composto sobre canvas.

Após a operação, o canvas de destino canvas possui o resultado da
composição e o canvas src não sofre qualquer alteração.
Fonte: http://www.telemidia.puc-rio.br/~francisco/nclua/referencia/canvas.html#function_compose

Exemplo:
<code>canvas -> 1920 x 1080
imagem -> 1280 x 720

canvas.compose(0, 0, imagem)
</code>
Como a imagem deve ser composta no canvas?

A imagem fica na posição 0,0 (esquerda/cima) com o tamanho original de 1280x720 e fica sobrando espaço embaixo e do lado direito.

A imagem começa na posição 0,0 (esquerda/cima) e é aumentada para preencher todo o tamanho do canvas (1920x1080).
Answer:
A imagem fica na posição 0,0 (esquerda/cima) com o tamanho original de 1280x720 e fica sobrando espaço embaixo e do lado direito.
O canvas não faz redimensionamento automático por padrão. Para redimensionar um canvas você pode tentar usar a função:  canvas:attrSize(height, width).


Reason for "Neural networks are exceptionally good at coming up with good features for highly structured data"

Question: I was reading about deep Q-learning and came across this statement

Neural networks are exceptionally good at coming up with good features
  for highly structured data

from this blog.
I want to why that happens and proof for that ?
Comment: It's from empirical observation from what I've seen, so you're not going to get a proof for this, at most some hypothesis. We have the universal approximation theorem, and not much besides that.
Answer: That quote is basically a tautological statement if you assume that the network converges to its true parameter values.
A neural network is defined as
$$
y = a(a(a(...a(a(X\Gamma_L)\Gamma_{L-1}...)\Gamma_3)\Gamma_2)\Gamma_1 + \epsilon
$$
Define
$$
V \equiv a(f(\Gamma_{2:L}, X))
$$
and
$$
\hat{y} = V\Gamma_1
$$
Those $V$ are derived features, related linearly to the outcome by weights $\Gamma$.  They are "good" features if $E[(y-\hat{y})^2]$ is small.  And this tends to be the case, because neural nets typically perform quite well once tuned adequately.
The statement is tautological because deriving features is precisely what a neural network does.  A neural net is basically a regressor-picker for OLS (or for penalized regression, or a penalized GLM).
(Obviously this is for the squared error loss, but the generalization to classification is simple).


Mudar coluna de date para timestamp

Question: Tenho uma tabela com uma coluna do tipo date mas preciso ver a informação do GMT, minha ideia é converter ela para timestamp. Como posso mudar isso mesmo que a coluna já contenha valor?
create table PRO_TFESTIVO
(
  oid_festivo      NUMBER(10) not null,
  fecha_hora_envio DATE to TIMESTAMP
)

Answer: Voce nao pode alterar o tipo de uma coluna DATE/TIMESTAMP sem:

Renomear a coluna (Ex: OLD_FECHA_HORA_ENVIO) com os valores existentes;
Criar uma nova coluna com o nome original (FECHA_HORA_ENVIO);
Preencher essa nova coluna com os valores existentes na tabela renomeada;
Remover a coluna (OLD_FECHA_HORA_ENVIO), pois nao iremos mais utilizar ela;

Converter de DATE para TIMESTAMP WITH TIME ZONE:
ALTER TABLE pro_tfestivo RENAME COLUMN FECHA_HORA_ENVIO TO OLD_FECHA_HORA_ENVIO;
ALTER TABLE pro_tfestivo ADD FECHA_HORA_ENVIO TIMESTAMP WITH TIME ZONE;
UPDATE pro_tfestivo SET FECHA_HORA_ENVIO = FROM_TZ(CAST(OLD_FECHA_HORA_ENVIO AS TIMESTAMP), 'GMT');
ALTER TABLE pro_tfestivo DROP COLUMN OLD_FECHA_HORA_ENVIO;

Extra :) Converter de TIMESTAMP WITH TIME ZONE para DATE:
ALTER TABLE pro_tfestivo RENAME COLUMN FECHA_HORA_ENVIO TO OLD_FECHA_HORA_ENVIO;
ALTER TABLE pro_tfestivo ADD FECHA_HORA_ENVIO DATE;
UPDATE pro_tfestivo SET FECHA_HORA_ENVIO = CAST(to_timestamp_tz(OLD_FECHA_HORA_ENVIO, 'dd/mm/yyyy hh24:mi:ssXFF TZR') at time zone 'GMT' AS DATE);
ALTER TABLE pro_tfestivo DROP COLUMN OLD_FECHA_HORA_ENVIO;

Mudar coluna de date para timestamp


React Native Image Position

Question: Is there a way how to control image position with resizeMode set to cover? I'm looking for similar result as can be achieve by using background-positon: center bottom in traditional CSS.
Here is an illustration of the situation:

Image with same dimensions as screen
Image with custom height, picture gets centered
(Desired) Image with custom height, but with picture aligned to the bottom edge of the element

My code:
<Image
    source={require('./eifell.jpg')}
    resizeMode={Image.resizeMode.cover}
    style={{
        height: 300
    }}
/>
Comment: are you sure with the numbering? you really want to achieve nr.3 in your picture, where the picture is out of frame?
Answer: I believe you'll have to achieve this by using the transforms prop on the image style and utilize the translateY transformation.
It will involve a little math... off the top of my head I believe you would need to follow these steps:

Use Image.getSize() to find the dimensions of your image
Then based on the size of your window from Dimensions.get('window') calculate how many pixels your image will scale to.
Find the difference between the height displayed (say 667px) and the desired height of the image (300px in your example)
Then translate the image up that many pixels.

React Native Image Position


Manually create Liferay login url

Question: Is there a way to create a Liferay login url if I know the site name, virtual host, username, etc...
I basically want to come up with some javascript that enables third-party sites to create a login box to my site, preferablty to a specific page
Just to clarify, I need a url that will log in the user with the parameters they type in text fields on the third party site. The third party site does not necessarily use Liferay so it cannot have a login portlet
Answer: I don't understand what you need...
Do you need http://virtualhostname/c/portal/login page?
Or you what to create a your own login page... e.g. creating a page with just the LOGIN portlet and provind a link to open it in Exclusive mode?
Or something else...?
Comment: The third party website the user will log in from will most likely not run Liferay so they can't add a login portlet
Comment: I'm saying that, creating a page with login portlet only, you can provide that link (in exclusive windowstate) to the other website... and it can embed the portlet inside a popup/iframe o what you need. Try adding parameter like "p_p_state=exclusive" to the page containing login portlet.
Comment: Yep, I did it that way
Answer: In a Liferay portlet, put that piece of code :
<code>            LiferayPortletURL urlLogin = PortletURLFactoryUtil.create(
                    request, "58", themeDisplay.getPlid(),
                    PortletRequest.ACTION_PHASE);
            urlLogin.setWindowState(LiferayWindowState.EXCLUSIVE);
            urlLogin.setParameter("_58_struts_action", "/login/login");
            urlLogin.setParameter("_58_login", _your_login);
            urlLogin.setParameter("_58_password",_your_password);
            urlLogin.setParameter("_58_rememberMeCheckbox", "false");
            urlLogin.setParameter("_58_redirect", _write_an_url_to_be redirected_after_successful_login);
            urlLogin.setParameter("_58_doActionAfterLogin", "false");
            urlLogin.setParameter("_58_saveLastPath", _your_previous_url);
</code>
58 is the portletId of the Liferay Login portlet.
Then, have a look at your urlLogin.toString() to understand how is it build.
Regards
Comment: I did that but the username/password are encrypted so I can't just set them as parameters in the url

Manually create Liferay login url


How to draw radial gradients in a CALayer?

Question: I know CAGradientLayer doesn't support radial gradient at the moment and only has option of kCAGradientLayerAxial.
I want something like below:

I have looked around for this issue and found that there is a way around this. But the explanations were not clear to me. So I want to know if I can draw radial gradients using CAGradientLayer and if so, then how to do it?
Comment: Why can't you use `CGContextDrawRadialGradient`? You can always render to an image, then assign it to the contents of a `CALayer`. Using `CALayer`'s `renderInContext:` is also an option, but it all leads to `CGContextDrawRadialGradient`.
Comment: @Mazyod I have multiple layers added as a sublayer to my UIView and I am drawing bezierPath on these layers. So all the the properties like solid fill, stroke width etc are associated with the layer. So just want to maintain the consistency in code.
Comment: @Mazyod Also I didn't get your concept of rendering to an image and then assigning it to the contents of a CALayer. Can you please elaborate a bit more.
Answer: From what I understood, you just need a layer that draws a gradient, and CGContextDrawRadialGradient works perfectly for that need. And to reiterate on what you said, CAGradientLayer doesn't support radial gradients, and nothing we can do about that, except unnecessary swizzling that can be done cleanly with a CALayer subclass.
(note: the gradient drawing code was taken from here. It isn't what this answer is about.)

viewDidLoad:
GradientLayer *gradientLayer = [[GradientLayer alloc] init];
gradientLayer.frame = self.view.bounds;

[self.view.layer addSublayer:gradientLayer];

CALayer subclass:
- (instancetype)init
{
    self = [super init];
    if (self) {
        [self setNeedsDisplay];
    }
    return self;
}

- (void)drawInContext:(CGContextRef)ctx
{

    size_t gradLocationsNum = 2;
    CGFloat gradLocations[2] = {0.0f, 1.0f};
    CGFloat gradColors[8] = {0.0f,0.0f,0.0f,0.0f,0.0f,0.0f,0.0f,0.5f};
    CGColorSpaceRef colorSpace = CGColorSpaceCreateDeviceRGB();
    CGGradientRef gradient = CGGradientCreateWithColorComponents(colorSpace, gradColors, gradLocations, gradLocationsNum);
    CGColorSpaceRelease(colorSpace);

    CGPoint gradCenter= CGPointMake(CGRectGetMidX(self.bounds), CGRectGetMidY(self.bounds));
    CGFloat gradRadius = MIN(self.bounds.size.width , self.bounds.size.height) ;

    CGContextDrawRadialGradient (ctx, gradient, gradCenter, 0, gradCenter, gradRadius, kCGGradientDrawsAfterEndLocation);

    CGGradientRelease(gradient);
}

Comment: @DrPatience the above code is directly applicable to swift. It would just be like ```override func drawInContext(ctx: CGContext!) { …```
Comment: @DrPatience Not sure the specific trouble you're running into, but maybe this will help? https://gist.github.com/MrBendel/f10d46a3160ffdf28989
Comment: how can this be achieved in SWIFT ?
Comment: thank you @AndyPoes I'm having trouble with this line >> "CGContextDrawRadialGradient(ctx, gradient, gradCenter, 0.0, gradCenter, gradRadius, kCGGradientDrawsAfterEndLocation)" and the the instance method
Comment: @AndyPoes fantastic, many thanks :). Is the init method also needed in swift ? and if so is there significant change to it, thanks.
Comment: I tried this but the gradient is showed above all the subview (UIButton, UILabels, etc), so their colors are "contaminated" by the gradient. Any clue to fix this?
Comment: @WedgeSparda That's not possible, unless those controls are non-opaque. Just make sure the `CALayer` is at the bottom of the `subLayers`.
Comment: How do we change the colors that it uses?
Comment: Radius should probably be max of half the width or height, i.e. MAX(width / 2, height / 2)
Comment: Is there any advantage of this method over the method mentioned by @rpstw? https://stackoverflow.com/a/52960769/89590 Setting `CAGradientLayer.type` to `.radial` seems to work fine.
Answer: Here is the Swift3 code I use :
import UIKit

class RadialGradientLayer: CALayer {

    required override init() {
        super.init()
        needsDisplayOnBoundsChange = true
    }

    required init?(coder aDecoder: NSCoder) {
        super.init(coder: aDecoder)
    }

    required override init(layer: Any) {
        super.init(layer: layer)
    }

    public var colors = [UIColor.red.cgColor, UIColor.blue.cgColor]

    override func draw(in ctx: CGContext) {
        ctx.saveGState()

        let colorSpace = CGColorSpaceCreateDeviceRGB()
        var locations = [CGFloat]()
        for i in 0...colors.count-1 {
            locations.append(CGFloat(i) / CGFloat(colors.count))
        }
        let gradient = CGGradient(colorsSpace: colorSpace, colors: colors as CFArray, locations: locations)
        let center = CGPoint(x: bounds.width / 2.0, y: bounds.height / 2.0)
        let radius = min(bounds.width / 2.0, bounds.height / 2.0)
        ctx.drawRadialGradient(gradient!, startCenter: center, startRadius: 0.0, endCenter: center, endRadius: radius, options: CGGradientDrawingOptions(rawValue: 0))
    }
}

Comment: Yep this worked for me. A couple notes:

- If you're coding in a mix and match project (Obj-C + Swift), defining an array of CGColors will throw an error since Objective-C doesn't allow you to create an array of primitive data types. To overcome this you can create an array of UIColors, and convert them to their cgColor values in the `draw` function.

- The circle this drew had jagged edges when added to a smaller subview. I fixed this by setting the layer's `masksToBounds = true`, then added added a corner radius to make the view containing the layer a circle, making the edge smooth.
Comment: this worked very well for me too - only things I changed were to use `max` instead of `min` for radius and use `.drawsAfterEndLocation` instead of `CGGradientDrawingOptions(rawValue: 0)` as that ended up in a more pleasing result (imho obvs)
Comment: You can add your created Radial `CALayer` like this: `view.layer.insertSublayer(gradientLayer, below: view.layer)`.
Answer: I don't know when but now you can change CAGradientLayer 's type to kCAGradientLayerRadialand it works.
Theoretically the performance of the Core Animation way is better than Core Graphics.
Some example code:
class View : UIView {

    let gradientLayer = CAGradientLayer()
    override init(frame: CGRect) {
        super.init(frame: frame)

        gradientLayer.startPoint = CGPoint(x: 0.5, y: 0.5)
        gradientLayer.endPoint = CGPoint(x: 1, y: 1)
        gradientLayer.locations = [
            NSNumber(value: 0.6),
            NSNumber(value: 0.8)
        ]
        gradientLayer.type = .radial
        gradientLayer.colors = [
            UIColor.green.cgColor,
            UIColor.purple.cgColor,
            UIColor.orange.cgColor,
            UIColor.red.cgColor
        ]
        self.layer.addSublayer(gradientLayer)
    }
    required init?(coder aDecoder: NSCoder) {
        super.init(coder: aDecoder)
    }

    override func layoutSublayers(of layer: CALayer) {
        assert(layer === self.layer)
        gradientLayer.frame = layer.bounds
    }
}

Comment: Works perfectly. But what do locations (0.6 & 0.8) and start/end points mean?
Comment: Much better. Thanks for adding this. Wouldn't have even checked for it.
Answer: Swift 5
import UIKit

final class RadialGradientLayer: CALayer {

    let centerColor: CGColor
    let edgeColor: CGColor

    init(centerColor: UIColor, edgeColor: UIColor) {
        self.centerColor = centerColor.cgColor
        self.edgeColor = edgeColor.cgColor
        super.init()
        needsDisplayOnBoundsChange = true
    }

    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }

    override func draw(in ctx: CGContext) {
        ctx.saveGState()
        let gradient = CGGradient(colorsSpace: CGColorSpaceCreateDeviceRGB(),
                                  colors: [centerColor, edgeColor] as CFArray,
                                  locations: [0.0, 1.0])

        let gradCenter = CGPoint(x: bounds.midX, y: bounds.midY)
        let gradRadius = min(bounds.width, bounds.height)

        ctx.drawRadialGradient(gradient!,
                               startCenter: gradCenter,
                               startRadius: 0.0,
                               endCenter: gradCenter,
                               endRadius: gradRadius,
                               options: .drawsAfterEndLocation)
    }
}


Regex remove all leading and trailing special characters?

Question: Let's say I have the following string in javascript:
&a.b.c. &a.b.c& .&a.b.c.&. *;a.b.c&*. a.b&.c& .&a.b.&&dc.& &ê.b..c&

I want to remove all the leading and trailing special characters (anything which is not alphanumeric or alphabet in another language) from all the words.
So the string should look like
a.b.c a.b.c a.b.c a.b.c a.b&.c a.b.&&dc ê.b..c

Notice how the special characters in between the alphanumeric is left behind. The last ê is also left behind.
Answer: This regex should do what you want. It looks for

start of line, or some spaces (^| +) captured in group 1
some number of symbol characters [!-\/:-@\[-``\{-~]*
a minimal number of non-space characters ([^ ]*?) captured in group 2
some number of symbol characters [!-\/:-@\[-``\{-~]*
followed by a space or end-of-line (using a positive lookahead) (?=\s|$)

Matches are replaced with just groups 1 and 2 (the spacing and the characters between the symbols).

let str = '&a.b.c. &a.b.c& .&a.b.c.&. *;a.b.c&*. a.b&.c& .&a.b.&&dc.& &ê.b..c&';
str = str.replace(/(^| +)[!-\/:-@\[-`\{-~]*([^ ]*?)[!-\/:-@\[-`\{-~]*(?=\s|$)/gi, '$1$2');
console.log(str);

Note that if you want to preserve a string of punctuation characters on their own (e.g. as in Apple & Sauce), you should change the second capture group to insist on there being one or more non-space characters (([^ ]+?)) instead of none and add a lookahead after the initial match of punctuation characters to assert that the next character is not punctuation:

let str = 'Apple &&& Sauce; -This + !That!';
str = str.replace(/(^| +)[!-\/:-@\[-`\{-~]*(?![!-\/:-@\[-`\{-~])([^ ]+?)[!-\/:-@\[-`\{-~]*(?=\s|$)/gi, '$1$2');
console.log(str);
Comment: This seems to be the best one liner way and it works perfectly for diacritics too. Thanks!
Comment: This removes characters from the middle of the string. It should only remove from end and beginning. Test with string like "Apple & Sauce", or "This + That"
Comment: @siefix *thank you* for leaving a comment to go with (what I presume is) your downvote. I believe the behaviour you describe is what OP asked for: "I want to remove all the leading and trailing special characters from **all** the words", not just the end and beginning of the string. Now we could argue as to whether `&` or `+` on their own should be stripped; they don't match the pattern of data in the question, but I think it's a reasonable interpretation of the wording of the question. Regardless, I've updated the answer with a regex that will not remove a string of punctuation on its own.
Comment: @Nick thanks for the update and additional solution. Yes I interpreted it as each was a separate distinct word, and the OP wanting to keep special characters in the middle (e.g. "a.b.&&dc"). Can see both ways.
Answer: a-zA-Z\u00C0-\u017F is used to capture all valid characters, including diacritics.
The following is a single regular expression to capture each individual word. The logic is that it will look for the first valid character as the beginning of the capture group, and then the last sequence of invalid characters before a space character or string terminator as the end of the capture group.

const myRegEx = /[^a-zA-Z\u00C0-\u017F]*([a-zA-Z\u00C0-\u017F].*?[a-zA-Z\u00C0-\u017F]*)[^a-zA-Z\u00C0-\u017F]*?(\s|$)/g;
let myString = '&a.b.c. &a.b.c& .&a.b.c.&. *;a.b.c&*. a.b&.c& .&a.b.&&dc.& &ê.b..c&'.replace(myRegEx, '$1$2');
console.log(myString);
Answer: Something like this might help:

const string = '&a.b.c. &a.b.c& .&a.b.c.&. *;a.b.c&*. a.b&.c& .&a.b.&&dc.& &ê.b..c&';
const result = string.split(' ').map(s => /^[^a-zA-Z0-9ê]*([\w\W]*?)[^a-zA-Z0-9ê]*$/g.exec(s)[1]).join(' ');
console.log(result);

Note that this is not one single regex, but uses JS help code.
Rough explanation: We first split the string into an array of strings, divided by spaces. We then transform each of the substrings by stripping
the leading and trailing special characters. We do this by capturing all special characters with [^a-zA-Z0-9ê]*, because of the leading ^ character it matches all characters except those listed, so all special characters. Between these two groups we capture all relevant characters with ([\w\W]*?). \w catches words, \W catches non-words, so \w\W catches all possible characters. By appending the ? after the *, we make the quantifier * lazy, so that the group stops catching as soon as the next group, which catches trailing special characters, catches something. We also start the regex with a ^ symbol and end it with an $ symbol to capture the entire string (they respectively set anchors to the start end the end of the string). With .exec(s)[1] we then execute the regex on the substring and return the first capturing group result in our transform function. Note that this might be null if a substring does not include proper characters. At the end we join the substrings with spaces.
Comment: This doesn't leave behind the last `ê`
Comment: Yes thats what I explained in the post. Anyway, I've edited it to also leave behing ``ê`` characters. You can edit the the special char capturing groups the specify which characters you consider special characters.
Comment: This works pretty well. Only problem is that the `ê` is variable. Like it could have any of those types of alphabets. `à` for example.
Comment: Well you could list all possible special characters explicitly, for a universal matching on those letters you would need to match ranges of unicode codes. See e.g. https://stackoverflow.com/a/280762/2692307 on how to match unicode ranges.
Comment: This is incorrect. It removes special characters from the middle of the string. Test with a simple string like "This + That"


How do I get all the referenced taxonomy terms without the field name?

Question: I have been looking into entityQuery but haven't seen what I am trying to do yet.
If I have a node object, is it possible to get all taxonomy terms referenced by the node object, regardless of the field they are in?
Most of what I have seen would be getting the terms from a specific field, but I won't have access to the field name. I just need to find all terms in a specific vocabulary that are referenced by the node. Thanks!
Comment: Any solution for this problem will include looping on all the fields of said node and checking if they are a taxonomy reference field.
Comment: Can you tell us the use case, why you can't be aware of the field name which referencing to the node? Maybe we could find another approach!
Of course we can solve this one as well, but maybe that would be easier.
Comment: I am looking at porting the Drupal 7 Parse.ly module and I need to add all the taxonomy terms of a specific vocabulary (or multiple) configured by the user to the metadata in the head of the page. I could add configuration to have the user give me the field name used, but was hoping there would be a good solution without that.
Answer: You can iterate through all the fields on the node and add conditions to check that the field is an entity reference field, and that the target type is taxonomy_term:
// Iterate through each field on the node entity to get all the tagged
// taxonomy terms on the node.
foreach ($entity->getFields() as $field) {
  // Only look for fields that are entity reference fields.
  if ($field instanceof EntityReferenceFieldItemList) {
    // Get the field settings.
    $field_definition = $field->getFieldDefinition();
    $target_type = $field_definition->getSetting('target_type');
    // Check that the field targets are taxonomy terms.
    if ($target_type == 'taxonomy_term') {

      // Do stuff..

    }
  }
}


Is it necessary to use UML diagram prior to php programing?

Question: I'm going to develop a small wordpress plugin in PHP. IS it necessary to create UML to create a good application. I think it as waste of time for small plugins. But in my plugin there are actor like visitor and admin role can take place. There can also be interaction between other author(actors in case of uml). Is UML is necessary here?
Is it necessary to be a professional?
Comment: You're asking for opinions. Do you draw up formal blueprints and run your plants past the municipal planning commission every time you want to nail two boards together? Feel free to if that's how you get your kicks. For "small" projects, it'd be a massive waste of time.
Comment: If you would set the question telling us what priorities and tasks do you have, and asking for what modelling diagrams will be useful for what reasons and on what stages, and what are your problems in using and understanding them, there could be some more fruitful discussion. Try to be maximally concrete.
Comment: I got you, it will be waste of time! thanks@Marc B
Answer: Absolutely not.  UML is only a tool for planning.
The only things required to develop a small wordpress plugin are
A Wordpress environment (LAMP, MAMP, ETC), access to that environment (Control Panel,FTP, SSH, Local FileSystem, ETC), and a bit of knowledge (PHP, WordPress).
Although planning is useful and can help you stay focused on the task at hand it certainly is not uncommon for professionals to forgo formalized planning and 'knock it out'
Comment: Fully agree with the answer! To much planning on a small project can actually kill your productivity.
Comment: I have knowledge in php,jquery,css,core java,bit mysql. I develope wordpress plugins. So without UML can i say, am a professional software developer? @Marc B
Comment: If you get paid for your work you are a professional.
Clients will eventually ask you about process and quality assurance , but they are tools to the end-goal.


Can I embed $\mathbb R^{\mathbb N}$ with a partial order into $^\ast\mathbb{R}$ with the linear order?

Question: Define a relation $\prec$ on  $\mathbb R^{\mathbb N}$ as,

For all $f, g \in \mathbb R^{\mathbb N} $, $f \prec g$, if for all $n \in \mathbb N$, $f(n) \leq g(n)$, and there exists a $m \in \mathbb N$ such that $f(m) < g(m)$.

Does there exist a function $u : \mathbb R^{\mathbb N} \to {^\ast\mathbb{R}}$ such that

For all $f, g \in \mathbb R^{\mathbb N} $,$f \prec g$ implies that $u(f) < u(g)$
  ?

${^\ast\mathbb{R}}$ denotes hyperreal numbers. I tagged economics, because this is an attempted extension of utility representation theorem.
Comment: @Regret It seems these are [hyperreal numbers](https://en.wikipedia.org/wiki/Hyperreal_number).
Comment: What is ${{}^\ast\Bbb R}$?
Comment: @dtldarek Thank you for answering this for me.
Answer: If I have understood the construction of ${}^\ast\Bbb R$ properly, then the function defined as follows should work.
$$u(f)_n=\sum_{k=0}^nf(k)$$
Here $u(f)_n$ denotes the $n$-th member of the hyperreal $u(f)$. If $f\prec g$, then $u(f)_n<u(g)_n$ for all $n\ge m$. There are cofinitely many $n$ greater than $m$, so regardless of the choice of ultrafilter, $u(f)<u(g)$.
Comment: Hi, thank you for your answer and sorry for my delay to response. As I can tell, I think your construction is correct.


Exporting fields of a highlighted row in Access Databse to a Word document

Question: I have an access database and I want to export fields from ONE highlighted row to a word document and email it to a recepient.
From the Access database I want to export the following fields:
Initials (character string), HospNo (Character and Number string), date, comment (character string)
and I want to export these fields from the row of my choice to a word document, c:\test.docx, with 4 MERGEFIELD's bookmarked as Inits, HosNumber, ScanDate, Diagnosis, respectively.
I think MailMerge is the solution and that's why I used Mergefileds in Word. But I know very little VBA and don't know where to start from.
I have Office 2010 on my PC.
Is that information sufficient to explain the problem?
Answer: From a very high level, you're probably going to need to create a recordset in VBA that contains just the one record you want to export.  You can then use that recordset as your source for your mailmerge.
I've never done mailmerges, but this should get you started:
<code>Dim db as Database
Dim rec as Recordset

Set db = CurrentDB
Set rec = db.OpenRecordset("SELECT Initials, HospNo, [date], comment FROM MyTableName WHERE SomeFilterCriteria")

'Mailmerge based on "rec"
</code>
Obviously you need to change MyTableName and MyFilterCriteria based on your specific info, you didn't give us the table name or how you want to determine which record of data to mailmerge.
Either that or you can build a query, set up the mailmerge from the query, and then put filters in the query that point to your form.  In the Criteria line in a query (if you open it in Design View), you would put something like
<code>[Forms]![MyFormName].[MyFieldName]
</code>
Also, if you have the ability to do so, change your date field name.  The word "date" is a reserved word, which means you have to enclose it in brackets so Access doesn't think it's a built-in command.  Change the field name to scandate or something to avoid future problems.
Comment: Thanks a lot, I ended up designing a form with a button that runs a procedure to send the fileds from that record being shown on the form as a word attachement in an email
Answer: If you are already working with MailMerge, you can just select the line in Access and use the Word Merge feature under the external data link.
If you are looking for a more automated procedure, I believe you will need to use code.


Link to download iTMSTransporter for windows 7?

Question: iTunes Store Transporter (Transporter) is Apple's Java-based command-line tool for sending content to the iTunes Store. You can use Transporter to deliver your pre-generated audio and video content, in an iTunes Store Package (iTP package), to the iTunes Store.
Whether you are a large label or an encoding house, you can use Transporter to ensure your metadata and assets are properly delivered to the iTunes Store, validating the iTP packages against Apple's specifications.
Can someone provide me link to download iTMSTransporter for windows 7.
I searched on net it only provides a .pkg file which is not opening in windows.
Answer: I guess Apple hide it. Go to https://itunesconnect.apple.com/transporter/, input what version you want.
ex:
https://itunesconnect.apple.com/transporter/1.8.3/iTMSTransporterToolInstaller_1.8.3.exe
Comment: Current version right now: iTMSTransporterToolInstaller_1.9.8.exe
Comment: I've found Transporter User Guide 2.0 https://help.apple.com/itc/transporteruserguide which has a section "Content-type details > Apps details". It has a link https://appstoreconnect.apple.com/WebObjects/iTunesConnect.woa/ra/resources/download/Transporter__OSX/bin/ where I replaced Transporter__OSX by Transporter__windows and downloaded 2.0.0. You can replace it by Transporter__linux to download Linux version as well.
Answer: iTMS is actually a part of Xcode and I'm afraid you cannot use it on a Windows machine natively at all.
Comment: Interesting.. I just noticed this in the help entry: `-WONoPause    The -WONoPause option is only valid on Windows...`
Comment: As far as I understand, it's a Java binary and can run on Windows. This guy seems to have it working: https://github.com/sshaw/itunes_store_transporter#readme
Answer: https://itunesconnect.apple.com/WebObjects/iTunesConnect.woa/ra/resources/download/TransporterUserGuide/pdf
which can be found on iTunes Connect referenced by other PDF files there clearly indicates there were versions for other OS's.
However they have either been unintentionally omitted from the present site or Apple's docs are outdated.


Git resolve conflict using --ours/--theirs for all files

Question: Is there a way to resolve conflict for all files using checkout --ours and --theirs? I know that you can do it for individual files but couldn't find a way to do it for all.
Comment: Does `git checkout --ours -- .` work? The `.` means the current directory, when applied from the working directory root, so it basically means the entire working directory. Not sure if that will work with the `--ours` flag though, and I'm not sure how it will handle deleted or renamed file conflicts.
Comment: @Cupcake I've used it successfully. Maybe that should be an answer?
Comment: If someone is looking for an answer to do this in Visual Studio, take a look at this:
https://stackoverflow.com/a/74605102/8644294
Answer: Just grep through the working directory and send the output through the xargs command:
grep -lr '<<<<<<<' . | xargs git checkout --ours

or
grep -lr '<<<<<<<' . | xargs git checkout --theirs

How this works: grep will search through every file in the current directory (the .) and subdirectories recursively (the -r flag) looking for conflict markers (the string '<<<<<<<')
the -l or --files-with-matches flag causes grep to output only the filename where the string was found. Scanning stops after first match, so  each matched file is only output once.
The matched file names are then piped to xargs, a utility that breaks up the piped input stream into individual arguments for git checkout --ours or --theirs
More at this link.
Since it would be very inconvenient to have to type this every time at the command line, if you do find yourself using it a lot, it might not be a bad idea to create an alias for your shell of choice: Bash is the usual one.
This method should work through at least Git versions 2.4.x
Comment: Instead of grepping, I think it's also possible to use [`git diff --name-only --diff-filter=U`](http://stackoverflow.com/a/10874862/559913).
Comment: Also `git status | grep both | awk '{print $3}' | xargs git checkout --[theirs|ours]`.  Quicker than grepping if you have a large project.
Comment: @joshbodily Nice. I don't have projects so huge that I would notice a difference, but I can see how it would be much faster especially if few files have changed compared to the total number in the directory----which _should_ be the case for normal commits.
Comment: Note that this does not work for rename/rename conflicts, e.g., `CONFLICT (rename/rename): Rename "a.txt"->"c.txt" in branch "HEAD" rename "a.txt"->"b.txt" in "master"`
Comment: Yet another option: `git status --porcelain | egrep '^UU' | cut -d ' ' -f 2 |xargs git checkout --[theirs|ours]`.
Comment: I had filenames with spaces and single quotes and I had to use the -z option on git diff in conjunction with the -0 option on xargs to get it to work. `git diff --name-only --diff-filter=U -z | xargs -0 git checkout --theirs`
Comment: Did not work probably because of spaces in my directory names
Comment: @AbdulHannan: You can escape the spaces in your filenames with a backslash: `file\ name\ with\ spaces.txt`
Or, enclose all pathnames in double quotes:
https://unix.stackexchange.com/questions/131766/why-does-my-shell-script-choke-on-whitespace-or-other-special-characters
Comment: @dimitri. Thats clear to me but how above answer can be made to work with directories containing spaces?
Comment: @AbdulHannan It shouldn't make a difference: grep should spit out an argument into the pipe that xargs + git can understand. At least it does on a UN*X system. Are you trying this on Windows?
Comment: Tried it on mac, will update you with what error I got exactly
Comment: For big projects this is really slow, it would also add jpegs and other files that didn't have conflicts. @Peter 's answer is the way to go.
Answer: You can -Xours or -Xtheirs with git merge as well. So:

abort the current merge (for instance with git reset --hard HEAD)
merge using the strategy you prefer (git merge -Xours or git merge -Xtheirs)

DISCLAIMER: of course you can choose only one option, either -Xours or -Xtheirs, do use different strategy you should of course go file by file.
I do not know if there is a way for checkout, but I do not honestly think it is terribly useful: selecting the strategy with the checkout command is useful if you want different solutions for different files, otherwise just go for the merge strategy approach.
Comment: Thanks, didn't know they have '--ours' and '--theirs' for merge. It seems that for merge they are actually not part of '-s' strategy but part of '-X' recursive options. '-s' version of ours actually just replaces all files without merging and theirs doesn't exist.
Comment: There is no `--theirs` or `--ours`-Option to git v1.9.4. An approach would be `git merge -s recursive -Xtheirs BRANCH`.
Comment: `--theirs` and `--ours` are not available neither with git `2.2.0`. Either my answer was not precise or they were available in older git version (this answer is pretty old in IT epoch). The right approach is with `-X`. I update accordingly
Comment: As of Version 2.4.0  --ours and --theirs are still very much available
http://git-scm.com/docs/git-checkout
Comment: Tried this, and got "automatic merge failed, fix conflicts". This command clearly doesn't work as intended, and I recommend avoiding it - too buggy.
Comment: Also works when `rebase`ing, although the identities of `ours` and `theirs` is switched (`Xours` means keep the changes from the branch being rebased **onto**).
Answer: git checkout --[ours/theirs] . will do what you want, as long as you're at the root of all conflicts. ours/theirs only affects unmerged files so you shouldn't have to grep/find/etc conflicts specifically.
Comment: `$ git checkout --ours` gives:
`fatal: '--ours/--theirs' cannot be used with switching branches`.  `git version 2.31.1
hub version 2.14.2`
Comment: For me this doesn't seem to recurse into subdirectories.
Comment: I get `error: path 'foo/bar/blah' does not have our version`.
Comment: You can also use `git restore [--ours] [--theirs] [--staged] `
Comment: I'm using git version 2.16.2.windows.1 and it works perfectly for me. Thanks!
Answer: git diff --name-only --diff-filter=U | xargs git checkout --theirs

Seems to do the job.  Note that you have to be cd'ed to the root directory of the git repo to achieve this.
Comment: I think this is a better answer than the top-voted one because (1) it applies to all files, not just the working directory; and (2) it won't have any brittleness around grepping for conflict markers.  The 'git diff' command here lists all unmerged paths, which is exactly what we want to checkout.
Comment: Nice! I was always concerned about the reliability of the conflict markers grep
Comment: I pieced exactly this together from above answers. Agreed this is the cleanest + most performant (the `grep` option is really a non-starter for larger projects, esp JS projects with sizeable `node_modules` folders). I ended up adding these aliases to my `.bashrc`:
```
alias git-co-ours="git diff --name-only --diff-filter=U | xargs git checkout --ours"
alias git-co-theirs="git diff --name-only --diff-filter=U | xargs git checkout --theirs"
```
Comment: You can use add `--relative` to diff `git diff --relative` to make the paths relative, then it works from any subdirectory.
Answer: Scenario 1
In case anyone else is looking to simply overwrite everything in one branch (e.g. master) with the contents of another branch, there's an easier way:
git merge origin/master --strategy=ours

(The --strategy option also works with git pull.)
Thanks to https://stackoverflow.com/a/1295232/560114
Scenario 2
For the other way around, see Is there a "theirs" version of "git merge -s ours"?
Update
For scenario 2, the linked answer recommends using:
git checkout branchA
git merge -X theirs branchB

I have found that this is not exactly the reverse of --strategy=ours and you might still get merge conflicts (and in some cases code from the other branch being kept that you actually wanted to remove). So if you want a solution to truly do the opposite of git merge other-branch --strategy=ours, the best way is to do it in two steps (two merges). Suppose your goal is to replace branch-a with the contents of branch-b. Then the first step would be to do this:
git checkout branch-b
git fetch branch-a
git merge branch-a --strategy=ours

Now branch-b is ready to merge into branch-a without conflicts. At this point, if you're using something like Github, you could raise a PR to merge branch-b into branch-a. Or if no peer review is required, you could do the merge directly:
git checkout branch-a
git merge branch-b

# Cleanup - delete branch-b (if desired)
git branch -d branch-b
git push origin --delete branch-b

Answer: function gitcheckoutall() {
    git diff --name-only --diff-filter=U | sed 's/^/"/;s/$/"/' | xargs git checkout --$1
}

I've added this function in .zshrc file.
Use them this way:
gitcheckoutall theirs or gitcheckoutall ours
Answer: Its simply one of these...
git checkout --ours .
git checkout --theirs .


UCS-2LE text file parsing

Question: I have a text file which was created using some Microsoft reporting tool. The text file includes the BOM 0xFFFE in the beginning and then ASCII character output with nulls between characters (i.e "F.i.e.l.d.1.").  I can use iconv to convert this to UTF-8 using UCS-2LE as an input format and UTF-8 as an output format... it works great.
My problem is that I want to read in lines from the UCS-2LE file into strings and parse out the field values and then write them out to a ASCII text file (i.e. Field1 Field2).  I have tried the string and wstring-based versions of getline – while it reads the string from the file, functions like substr(start, length) do interpret the string as 8-bit values, so the start and length values are off.
How do I read the UCS-2LE data into a C++ String and extract the data values?  I have looked at boost and icu as well as numerous google searches but have not found anything that works.  What am I missing here?  Please help!
My example code looks like this:
wifstream srcFile;
srcFile.open(argv[1], ios_base::in | ios_base::binary);
..
..
wstring  srcBuf;
..
..
while( getline(srcFile, srcBuf) )
{
    wstring field1;
    field1 = srcBuf.substr(12, 12);
    ...
    ...
}

So, if, for example, srcBuf contains "W.e. t.h.i.n.k. i.n. g.e.n.e.r.a.l.i.t.i.e.s." then the substr() above returns ".k. i.n. g.e" instead of "g.e.n.e.r.a.l.i.t.i.e.s.".
What I want is to read in the string and process it without having to worry about the multi-byte representation.  Does anybody have an example of using boost (or something else) to read these strings from the file and convert them to a fixed width representation for internal use?
BTW, I am on a Mac using Eclipse and gcc.. Is it possible my STL does not understand wide character strings?
Thanks!
Answer: Having spent some good hours tackling this question, here are my conclusions:

Reading an UTF-16 (or UCS2-LE) file is apparently manageable in C++11, see How do I write a UTF-8 encoded string to a file in Windows, in C++
Since the boost::locale library is now part of C++11, one can just use codecvt_utf16 (see bullet below for eventual code samples)
However, in older compilers (e.g. MSVC 2008), you can use locale and a custom codecvt facet/"recipe", as very nicely exemplified in this answer to Writing UTF16 to file in binary mode
Alternatively, one can also try this method of reading, though it did not work in my case. The output would be missing lines which were replaced by garbage chars.

I wasn't able to get this done in my pre-C++11 compiler and had to resort to scripting it in Ruby and spawning a process (it's just in test so I think that kind of complications are ok there) to execute my task.
Hope this spares others some time, happy to help.
Answer: substr works fine for me on Linux with g++ 4.3.3. The program
#include <string>
#include <iostream>

using namespace std;

int main()
{
  wstring s1 = L"Hello, world";
  wstring s2 = s1.substr(3,5);
  wcout << s2 << endl;
}

prints "lo, w" as it should.
However, the file reading probably does something different from what you expect. It converts the files from the locale encoding to wchar_t, which will cause each byte becoming its own wchar_t. I don't think the standard library supports reading UTF-16 into wchar_t.
Comment: Thanks for the reply.  I see the same behavior.  As you say, I don't think the UTF-16 to wchar_t is supported.  I used iconv to convert the file to UFT-8 and it solved by problem.
Comment: Although I'm probably addressing ghosts here, @Cryptik should mark his question as solved :)

UCS-2LE text file parsing


How to pass an EAV value to the Paypal payment information

Question: I've introduced a custom EAV attribute for the customer object. Let's call it myvalue. Within several places in magento, I'm printing the value like this:
echo Mage::getSingleton('customer/session')->getCustomer()->getMyvalue();

When the customer pays with paypal, I'd like to have myvalue in the reason as an addition to the order number. My intent is to match the order with some shop-side process.
So, how can I pass myvalue to paypal to make it visible together with the order number?
Comment: What Paypal method are you using?
Comment: It's Paypal Standard.
Answer: You can try to override the class Mage_Paypal_Block_Standard_Redirect into something like this:
protected function _toHtml()
{
    $standard = Mage::getModel('paypal/standard');

    //...

    foreach ($standard->getStandardCheckoutFormFields() as $field=>$value) {
        if ($field == 'REASON_CODE') {
            $myvalue = Mage::getSingleton('customer/session')->getCustomer()->getMyvalue();
            $value .= $myvalue;
        }
        $form->addField($field, 'hidden', array('name'=>$field, 'value'=>$value));
    }

    //...

    return $html;
}

I have added a condition in the foreach to edit the reason with your special customer value.
I don't know what is the code for the reason you speak about, if you don't as well you can first log that in the foreach:
Mage::log($field);
Mage::log($value);

Then don't forget to edit 'REASON_CODE' and getCustomer()->getMyvalue() in my example.


Spring Boot Actuator port when deployed to external Tomcat container

Question: I have a Spring Boot application that is deployed to an external Tomcat container (not using the embedded container), and am trying to get the actuator set up. The problem is that the management.port in application.properties does not seem to be honored by Tomcat. When I run Spring Boot with embedded Tomcat it works just fine.
For example, having the following set in application.properties:
management.port=9010
Working endpoints for embedded container

http://localhost:9010/health

Non-working endpoints for external container running on port 8080

http://localhost:9010/health
http://localhost:8080/health
http://localhost:9010/<appName>/health
http://localhost:8080/<appName>/health

Is there a special configuration I need in the Tomcat container to expose a Spring Boot actuator end point?
I've tried setting an environment variable of MANAGEMENT_PORT. Most (almost all) of the documentation available is using the embedded Tomcat, so tracking down this issue has proved to be challenging.
The third comment on this answer provided some possible insight: https://stackoverflow.com/a/28689853/2601060, which points to a GitHub file indicating that if the management port is not set, it will be the same as the server port.
Comment: The link you posted has an answer explaining that a separate instance is used for the actuator when using the embedded tomcat. Presumably that won't work when deploying to an external tomcat. There may be a way to achieve what you want to do, but it'll have to be in your external tomcat configuration, the properties for the embedded tomcat won't work.
Comment: @ci_ thanks for the response - are you aware of any way to configure that in the external tomcat?
Comment: Unfortunately not, or I would have posted an answer. I just commented to point you in the right direction. We use a separate context path for the actuators here, not a separate port.
Answer: We cannot specify an additional port with an external Tomcat container.
Here is why : https://github.com/spring-projects/spring-boot/issues/552
The only way is to extend the endpoints using a context path, say "/management" and apply security on it.
Answer: Yes, if your application.properties is having property called
"management.port: 9001" and "server.port: 9000". Then your application end-points will deploy on port 9000 and actuator end-points will deployed on port 9001.
So its up to us. We can mention both properties with same port, application will works correctly.
Answer: I had same issue in my local environement ,

I fixed it by changing the tomcat , (reinstalling a new one ),
also by changing the default port in > \apache-tomcat-9.0.52\conf\serve.xml to 8082
-and then you can access to yout actuator link : localhost:8082/yourwarName/actuator/health

:) hope it helps someone one day..
Answer: What Java version are you running Tomcat7 under?
N.B. This is all speculation - I haven't been able to verify this yet
If it's Java6 (and I'm guessing it is because I'm getting a similar issue), I suspect it's related to the following message:

INFO: JSR 356 WebSocket (Java WebSocket 1.1) support is not available
  when running on Java 6. To suppress this message, run Tomcat on Java
  7, remove the WebSocket JARs from $CATALINA_HOME/lib or add the
  WebSocket JARs to the tomcat.util.scan.DefaultJarScanner.jarsToSkip
  property in $CATALINA_BASE/conf/catalina.properties. Note that the
  deprecated Tomcat 7 WebSocket API will be available.

I can only hazard a guess, that Spring Boot use's JSR356 to tell the Web App Container to "in addition to listening to the default port for the main app, also listen on port X for actuator endpoints"... and this isn't available running under Java6... I'm probably wrong.
If anyone could confirm/deny this behaviour, I'll update this response.
After setting Tomcat to use Java8, and removing the socket jars (tomcat7-websocket.jar & websocket-api.jar jars), I get the following message from Spring:

o.s.b.a.a.EndpointWebMvcAutoConfiguration : Could not start embedded management container on different port (management endpoints are still available through JMX)

In the meantime, @DecipherX's workaround (i.e. don't set management.port=9010) will expose your actuator endpoints through the default port.
Answer: If you remove the management.server.port from your configuration, the actuator will be deployed under the servlet context path in external Tomcat.
http://<--domain-->/<--servlet-context-->/actuator/health

Unless the management port has been configured to expose endpoints by using a different HTTP port, management.endpoints.web.base-path is relative to server.servlet.context-path (Servlet web applications) or spring.webflux.base-path (reactive web applications). If management.server.port is configured, management.endpoints.web.base-path is relative to management.server.base-path.


How to write I vii°6 I6 with the outer voices in parallel 10ths

Question:
I know that V43 is a better option but the exercise I am doing does not allow me the option of inverted 7 chords. Can someone please correct me if I have made a mistake?
Comment: Related question given the nature of armani's proposed part-writing solution here: https://music.stackexchange.com/questions/118251/under-what-circumstances-can-a-dimished-5th-move-to-a-perfect-5th-in-voice-leadi
Comment: Dekka that is not the same at all. In the other question I thought it might be nice to get a list of exceptions going ... that is a general question regarding those two intervals, it just happens to use that progression.
Comment: are the 2notes in the bass line also eighth notes? Are the Roman numbers given or is this your task? If you are free you can treat the melody note C in B-C-D as passing tone.
Answer: Depends on what the grader is looking for, but unfortunately I do see indirect crossed voices with the alto voice going to the C which crosses the soprano's B in the first beat. I to vii6 is quite tricky for sure.
Answer: I don't see any problems here! You obviously can't double the F♯, and doubling the bass A would lead to parallels, so your only option is to double the C.
But there is one caveat: some traditions are really strict about motion from a diminished fifth to a perfect fifth, and thus they may view the upper-voice motion (soprano and tenor) moving into the I6 to be an error. I don't remember what Aldwell and Schachter say, but you'll want to clarify that they "allow" this if you're trying to follow that book exactly.
For me, I see this motion far too often in the literature to treat it as a part-writing error. There are chords later on where you can't resolve the tritone "correctly," and for that reason I personally think outlawing d5–P5 motion is pretty unnecessary.
Comment: They say that because of the parallel 10ths in the outer voices the D5 is allowed to move to a P5.


Django: How to provide a category that changes at runtime in the urls.py?

Question: I am trying to create a new URL level in my django-powered ecommerce site, meaning if a user is in domain.com/category/foo/ I am trying to add the next level down, in which they click on some element in foo and wind up in domain.com/category/foo/tag/bar/.  To that end, I have created my urls.py line for detecting this, and I believe there is no problem here:
(r'^category/(?P<category_slug>[-\w]+)/tag/(?P<tag_slug>[-\w]+)/$', 'show_tag', {
'template_name':'catalog/product_list.html'},'catalog_tag'),

Once the request has been mapped through the urls.py, I know it is going to need some variables from views.py in order for get_adsolute_url to do its thing, so I create the view:
def show_tag(request,
                  tag_slug,
                  template_name="catalog/product_list.html"):
    t = get_object_or_404(Tag,
                          slug=tag_slug)
    products = t.product_set.all()
    page_title = t.name
    meta_keywords = t.meta_keywords
    meta_description = t.meta_description
    return render_to_response(template_name,
                              locals(),
                              context_instance=RequestContext(request))

And lastly, in my Tag model, I set up my get_absolute_url to fill the keyword arguments:
@models.permalink
    def get_absolute_url(self):
        return ('catalog_tag', (), { 'category_slug': self.slug, 'tag_slug': self.slug })

I made sure the category and tag I'm about to request exist, and then I type domain.com/category/foo/tag/bar and I receive a
TypeError at /category/foo/tag/bar/
show_tag() got an unexpected keyword argument 'category_slug'

I believe I know where the error is, but I don't know how to solve it.  my get_abolute_url sets 'category_slug': self.slug but that definition, as I said, lives in my Tag model.  My Category model lives in the same models.py, but how do I tell my get_absolute_url to go find it?
Answer: Your view show_tag must have a parameter to accept the category_slug which is not there right now:
def show_tag(request,
    category_slug, tag_slug,
    template_name="catalog/product_list.html")

Comment: Indeed that was the case.  I was so tunnel-visioned on "fixing" the `get_absolute_url` I just stopped looking everywhere else.  Thank you Aamir!
Comment: Well sometimes it happens, although the error is exactly pointing you where the problem is.
Comment: Yes, but I foolishly thought the error was occurring in the view because it was being provided the wrong information, not improperly configured to accept information.


Find an equation of the tangent line to the hyperbola $x^2 - y^2 = 1$ that passes through the point (1,2)

Question: My friends are discusing this question but They don't agree with my answer, and They don't know how to solve.
My answer was
$y = x+3/2$
Comment: Well an obvious difficulty with your answer is that it does not pass through $(1,2)$...
Comment: Your equation is still not satisfied by $(1,2)$. It would seem that your friends are right to disagree with your solution.
Comment: Possible duplicate of [general equation of a tangent line to a hyperbola](https://math.stackexchange.com/questions/214977/general-equation-of-a-tangent-line-to-a-hyperbola)
Comment: the curve in your title is a circle
Comment: @WillJagy sorry, already fixed it
Comment: sorry again, I fixed the equation again
Comment: hjx, draw a careful picture. The edit you made 40 seconds ago gives a question with an answer... Not the answer you wrote, of course
Comment: @WillJagy now it is right, sorry
Comment: As a simple drawing shows, there should be four answers to this question (i.e. four different tangents). One of them is the the vertical line $x=1$, which is tangent to the hyperbola at $(1,0)$ and passes by the given point $(1,2)$.
Comment: @AndersBeta I disagree. I think there will be 2 tangents (try making a crude graph)
Comment: It is not possible to find a real equation of the tangent line to the hyperbola  x^2−y^2=1  that passes through the point (1,2).
Answer: The line x=1 is an obvious solution.
For other solutions, find the slope of tangent in two ways and make them equal to find the equation.
Answer: To find a tangent line, you would have to take a derivative. Implicitly.
$$x^2-y^2=1$$
$$2x-2yy'=0$$
$$y'=\frac{x}y=\frac{x}{\pm\sqrt{x^2-1}}$$
We use point-slope form to find the equation of a tangent line. For our purposes the point of tangency will be $(a, \pm\sqrt{a^2-1})$. The plus will be for the top, and the minus for the bottom point of tangency. (Because the positive square root represents the top half of the graph after solving for y, and vice versa for the bottom)
$$y-\sqrt{a^2-1}=\frac{a}{\sqrt{a^2-1}}(x-a)$$
This equation satisfies the point $(1,2)$.
$$2-\sqrt{a^2-1}=\frac{a}{\sqrt{a^2-1}}(1-a)$$
Multiply
$$2\sqrt{a^2-1}-(a^2-1)=a-a^2$$
Rearrange
$$a-1=2\sqrt{a^2-1}$$
Square both sides (This cancels out the plus-or-minus effect!)
$$a^2-2a+1=4a^2-4$$
$$3a^2+2a-5=0$$
$$(3x+5)(x-1)=0$$
Our final two points of tangency are $a=-\frac53$ and $a=1$.
Our tangent lines must be:
$$y-0=\frac10(x-1)\ \rightarrow\ x=1$$
$$y-(-\frac43)=\frac{\frac53}{\frac43}(x-(-\frac53))\ \rightarrow\ y=\frac54x+\frac34$$
Edit [Mohammad Riazi-Kermani]: Note that the lines pass through the point $(1,2)$.
The top point uses the positive y-coordinates. Also, a slope of infinity...
The bottom point uses the negative y-coordinates.
Comment: Yes, the line $x=1$ is an obvious solution. Now you can see the other tangent line, and how to get it. Hope this helps! At least, I had fun solving it...
Comment: everything is easy after it gets done, the hardness is doing for the first time. As a teacher of mine used to say, thanks.
Answer: $$\frac{x^2}{1^1}-\frac{y^2}{1^2}=1$$
Suppose the slope of the tangent is $m^{1}$, then the tangent passes through $P(1,2)$
Equation of tangent is $$y-2=m(x-1)=mx-m$$
$$y=mx+(2-m)$$
Condition for tangency is $c^2=a^2m^2-b^2$
$$(2-m)^2=m^2-1$$
$$4+m^2-4m=m^2-1$$
$$4m=5$$
$$m=\frac54$$
Substituting $m=\frac54$ in $y-2=mx-m$ we get,
$$y=\frac54x+\frac34$$
Comment: This is not a complete solution, since it misses the vertical line $x=1$.