Restrict access to webform submission nodes for anonymous

Question: I have a webform in my drupal website. I am uploading a text and pdf file through it. Now I am displaying all the content in a list using a block which is accessible for everyone. It's working fine.
So for every submission there is of-course a node created dynamically. Like - http://localhost/mysite/webform/upload/submissions/3
So it can be 3, 4, 5 whatever as uploading goes on. Now i have to restrict the access of these nodes / url pattern only to admin. I have tried every thing i found in webform settings configuration. No Luck !!!
One thing i can do is add css to hide that, but i dont think its the way to do it.
So, Any help would be appreciated. Thank You.
Comment: What is the webform version?
Answer: In Webform (i checked version 5.8) you can do the following.

Go to the form in question, to the settings tab, and then the access tab
You can click and tune "view any submissions" and set it to the "admininstrator" role
You can also tune the area  "view own submissions"
You can do the same thing via main permissions page (/admin/people/permissions)


Programmatically work with the Vim command mini-buffer

Question: I think my problem here may be that I don't have the correct terminology to search.  I want to write a plugin that is interactive in the little mini-buffer area (in Emacs terminology, sorry) at the bottom of the window, where your cursor is placed when you type : to enter command mode.  Plugins like FuzzyFinder and ctrlp seem to open a new buffer, but ideally I'd like to just share the command area, if that is possible, since what I want to do will always fit on a single line.
Does Vimscript allow this area to be used, much like Vim's own built-in wildmenu works?  Opening a new split buffer just feels kinda clunky for what I want to do.
Happy to do the reading of the documentation myself, I just don't really have an entry point at the moment.
Answer: That's the command-line.
See this Vim wiki page about input(). What kind of things do you want to do?
Comment: Thanks.  Got as far as playing around with `getchar()`, though I may be heading down the wrong path. I'm looking to write my own take on fuzzy finding of files/buffers, partly for learning and partly because I don't like ctrlp/fuzzyfinder's approaches. Effectively once my function is started, each keypress in the command line will be read and the fuzzy search continued. Following the cursor, the best completion (in the current directory) will be selected, then the other matches following thereafter, truncated with `...`. Some other key mappings added once the basic idea is working.
Comment: What I'm failing to fathom out, is how to effectively rewrite what is in the command line after each key press (i.e. insert the fuzzy completions). I'm just reading lots of help pages at the moment :)


Java Threads (multithreading)

Question: How can I give input to threads in java
eg:
class BTT extends Threads
{
  int ag1;
  int ag2;

  void build(int k)
  {
     void build(k+1);
  }
}

I want to set the values of ag1 and k in build different in different threads. How can i do that?
Comment: Can you please elaborate a bit?  Also, please format the code so that it becomes easy to understand.
Comment: true I find it good system to appeal to the ego of devloppers to encourage them to have rewards when they answer ^^, but I don't think it should prevent from helping out.
Comment: http://meta.stackexchange.com/questions/66773/should-mods-delete-work-on-that-accept-rate-comments
Comment: @user440336 - it is not about prevention.  It is about people deciding for themselves how helpful they want to be to someone who is breaching etiquette.
Answer: you treat your thread class as a simple POJO only (Java object) which can multiple values, i don't think that there should be such a big problem.
you can use something like the code below.
public class P1 extends Thread {

    private int age;

    public P1(int age) {
        this.age = age;
    }

    public void run() {
        System.out.println(this.age);
    }
    public static void main(String[] args) {
        P1 p1 = new P1(1);
        p1.start();
    }
}

Comment: Please check program http://pastebin.com/wdsAxEQ6. The value of count is 1705 if I am not use threads but if i use thread the value of the count is > 1705. Is there away where i can make int count shared by two threads? I am doing anything wrong in the program?
Answer: well when you create your thread you can do things like
MyThread mt = new MyThread(agr1, arg2);

mt.setValue(k);

but Java Threads usually uses Runnables
http://www.javabeginner.com/learn-java/java-threads-tutorial
in that case you can do the same
MyRunnable mr = new MyRunnable(arg1,arg2);
mr.setValue(k);

new Thread(mr).start();

Jason
Comment: Please check program  http://pastebin.com/wdsAxEQ6 . The value of count is 1705 if I am not use threads but if i use thread the value of the count is > 1705. Is there away where i can make int count shared by two threads? I am doing anything wrong in the program?

Java Threads (multithreading)


SwiftUI issues with Observed object

Question: I am having problems getting ObservedObject to work. In this example I have a TabView with a Home and Settings tabs. On the Settings tab I have a button to toggle a bool to set if I purchased to remove ads or not.
The AdView text has an if condition, on an ObservedObject, but when I toggle the value the ad text doesn't go away / appear. If I close the app and re-launch, it updates correctly. How can I get this to update in realtime?
class Settings: ObservableObject {
@Published var purchasedRemoveAds: Bool {
    didSet {
        UserDefaults.standard.set(purchasedRemoveAds, forKey: "purchasedRemoveAds")
    }
}

init() {
    self.purchasedRemoveAds = UserDefaults.standard.bool(forKey: "purchasedRemoveAds")
  }
}

struct ContentView: View {

@State var tabSelect: Int
@ObservedObject var settings: Settings

var body: some View {
    TabView(selection: $tabSelect) {
        NavigationView {
            Home()
        }
        .tabItem {
            Image(systemName: "house")
            Text("Home")
        }
        .tag(0)

        NavigationView {
            SettingsView(settings: Settings())
        }
        .tabItem {
            Image(systemName: "gearshape")
            Text("Settings")
        }
        .tag(1)
    }

    //Show Ads at bottom of screen
    if !settings.purchasedRemoveAds {
        Text("AdView here").frame(height: 50).frame(maxWidth: .infinity).background(Color.green)
    }
    Spacer()
  }
}

struct SettingsView: View {
@ObservedObject var settings: Settings

var body: some View {
    List {

        Section(header: Text("In-App Purchases")) {
            Button {
                settings.purchasedRemoveAds.toggle()
            } label: {
                Text("Remove Ads")
            }
        }.listRowBackground(Color.gray.opacity(0.1))

    }
    .navigationTitle("Settings")
}

}
Comment: Use AppStorage or a get and set instead of a didSet
Answer: On this line, you're creating a new instance of Settings:
SettingsView(settings: Settings())

Because this instance of Settings is instantiated before the switch is changed, it has no idea that the UserDefaults have been adjusted.
Instead, pass the existing instance:
SettingsView(settings: settings)

Also, look into @AppStorage where you can get some of this behavior for free from the system.
Comment: Perfect, thank you!

SwiftUI issues with Observed object


django 404 when opening static folder

Question: I have created a /static/ folder in my project's root and changed the settings thusly:
STATIC_URL = '/static/'

STATICFILES_DIR = [os.path.join(BASE_DIR, "static")]

But when I open my localhost/static, it produces a 404 error. Why is that?
Answer: For Django 1.3+:
STATICFILES_FINDERS = [
    'django.contrib.staticfiles.finders.FileSystemFinder',
    'django.contrib.staticfiles.finders.AppDirectoriesFinder',
]

STATICFILES_DIRS = [
    os.path.join(BASE_DIR, "static")
]

STATIC_ROOT = path.join(TOP_DIR, 'staticfiles')
STATIC_URL = '/static/'

For apache:
Alias /static /var/my/site/static
<Directory /var/my/site/static>
        Require all granted
</Directory>

Answer: Are you aiming at a particular file? If not then theres your problem, if you are aiming at a file, are you sure its in the correct directory?
Comment: No I'm trying to open a particular file (static/css/main.css)
Comment: @chubak - try printing os.path.join(BASE_DIR, "static") from somewhere in your code and watch the debug out put.

Also, what version of django are you running? I'm not sure why you'd have submodules of staticfiles rather than just
django.contrib.staticfiles

which is what the docs specify
Answer: You have to run manage.py collectstatic first.
Note: It's also possible that going to /static is the cause (missing the trailing slash) though django should redirect.
Comment: I ran collectstatic, still, I get 404 when I try to access /static/css/main.css
Comment: Do you have this in your urls.py file? `from django.contrib.staticfiles.urls import staticfiles_urlpatterns urlpatterns += staticfiles_urlpatterns()`

django 404 when opening static folder


why regularization is slower slope and not higher?

Question: I am reading about regularization in Aurelien Geron's book. I do understand that given a model $\beta_0$+ $x$ $\beta_1$ , regularization means:

If we allow the algorithm to modify $\beta_1$ but we force it to keep
  it small, then the learning algorithm will effectively have somewhere
  in between one and two degrees of freedom.

My question comes for the next figure where he shows his 3 models:

Why regularization reduces the risk of overfitting?
I think he just chose the red points (missing data) to specifically favour him... If his red points were to be on the oposite side he would have been better off with a higher slope (not a smaller one).
For example :

(I train and fit only on the blue dots, I do not see the red points)
Here, Having a slower slope would definetely not help to generalize better. On the other hand a higher slope will definetly reduce the risk of overfitting...
I don't see how having a smaller slope will help in generalizing better? He says this , but I don't see it...

You want to find the right balance between fitting the training data
  perfectly and keeping the model simple enough to ensure that it will
  generalize well.

The way I see it is that if you have few data points, your missing data can be better fitted equaly likely with either a higher or lower slope? Why is a lower slope considered it "better"?
Comment: I don't have the book, so I wonder about the context. Normally regularisation is applied in the framework of model selection, i.e., deciding how many variables/degrees of freedom you need. Without that context it doesn't make much sense to me to just make up some blue and red points, assume that only the blue ones have been analysed, and then show red ones that would indicate a smaller slope. If you just fit a single simple regression without any model selection, there is no need to regularise.
Comment: [Josh Starmer's this StatQuest video](https://www.youtube.com/watch?v=Q81RR3yKn30) helped me understand some of these concepts in a very relatable way. There are multiple follow up videos on Lasso, Ridge and Elastic regression approaches.
Answer: 1.a Related to the Variance/Bias trade off.
Bias / variance tradeoff math
You could see the regularization as a form of shrinking the parameters.
When you are fitting a model to data then the you need to consider that your data (and your resulting estimates) are made/generated from two components:
$$ \text{data $=$ deterministic part $+$ noise }$$
Your estimates are not only fitting the deterministic part (which is the part that we wish to capture with the parameters) but also the noise.
The fitting to the noise (which is overfitting, because we should not capture the noise with our estimate of the model, as this can not be generalized, has no external validity) is something that we wish to reduce.
By using regularization, by shrinking the parameters, we reduce the sample variance of the estimates, and it will reduce the tendency to fit the random noise. So that is a good thing.
At the same time the shrinking will also introduce bias, but we can find some optimal amount based on some computations with prior knowledge or based on data and cross validation. In the graph below, from my answer to the previously mentioned question, you can see how it works for a single parameter model (estimate of the mean only), but it will work similarly for a linear model.

1.b On average, shrinking the coefficients, when done in the right amount, will lead to a net smaller error.
Intuition: sometimes your estimate is too high (in which case shrinking improves), sometimes your estimate too low (in which case shrinking makes it worse).
Note that shrinking the parameter does not equaly influence those errors... we are not shifting the biased parameter estimate by some same distance independent from the value of the unbiased estimate (in which case there would be indeed no net improvement with the bias)
We are shifting with a factor that is larger if the estimate is larger away from zero. The result is that the improvement when we overestimated the parameter is larger than the detoriation when underestimated the parameter. So we are able to make the improvements larger than the detoriations and the net profit/loss will be positive
In formula's: The distribution of some non-biased parameter estimate might be some normal distribution say:$$\hat\beta\sim\mathcal{N}(\beta, \epsilon_{\hat\beta}^2)$$
and for a shrunken (biased) parameter estimate is
$$c\hat\beta \sim \mathcal{N}(c\beta,  c^2\epsilon_{\hat\beta}^2)$$
These are the curves in the left image. The black one is for the non-biased where $c=1$. The mean total error of the parameter estimate, a sum of bias and variance, is then
$$E[(c\hat\beta-\beta)^2]=\underbrace{(\beta-c\beta)^2 }_{\text{bias of $\hat\beta$}}+\underbrace{ c^2 \epsilon_{c\hat\beta}^2}_{\text{variance of $c\hat\beta$}}$$with derivative
$$\frac{\partial}{\partial c} E[(c\hat\beta-\beta)^2]=-2\hat\beta(\beta-c\beta)+2 c\epsilon_{c\hat\beta}^2$$
which is positive for $c=1$ which means that $c=1$ is not an optimum and that reducing $c$ when $c=1$ leads to a smaller total error. The variance term will relatively decrease more than the bias term increases (and in fact for $c=1$ the bias term does not decrease, the derivative is zero)
2. Related to prior knowledge and a Bayesian estimate
You can see the regularization as the prior knowledge that the coefficients must not be too large. (and there must be some questions around here where it is demonstrated that regularization is equal to a particular prior)
This prior is especially useful in a setting where you are fitting with a large amount of regressors, for which you can reasonably know that many are redundant, and for which you can know that most coefficients should be equal to zero or close to zero.
(So this fitting with a lot of redundant parameters goes a bit further than your two parameter model. For the two parameters the regularization doesn't, at first sight, seem so, useful and in that case the profit by applying a prior that places the parameters closer to zero is only a small advantage)
If you are applying the right prior information then your predictions will be better. This you can see in this question Are there any examples where Bayesian credible intervals are obviously inferior to frequentist confidence intervals
In my answer to that question I write:

The credible interval makes an improvement by including information about the marginal distribution of $\theta$ and in this way it will be able to make smaller intervals without giving up on the average coverage which is still $\alpha \%$. (But it becomes less reliable/fails when the additional assumption, about the prior, is not true)
In the example the credible interval is smaller by a factor $c = \frac{\tau^2}{\tau^2+1}$ and the improvement of the coverage, albeit the smaller intervals, is achieved by shifting the intervals a bit towards $\theta = 0$, which has a larger probability of occurring (which is where the prior density concentrates).

By applying a prior, you will be able to make better estimates (the credible interval is smaller than the confidence interval, which does not use the prior information). But.... it requires that the prior/bias is correct or otherwise the biased predictions with the credible interval will be more often wrong.
Luckily, it is not unreasonable to expect a priori that the coefficients will have some finite maximum boundary, and shrinking them to zero is not a bad idea (shrinking them to something else than zero might be even better and requires appropriate  transformation of your data, e.g. centering beforehand). How much you shrink can be found out with cross validation or objective Bayesian estimation (to be honest I do not know so much about objective Bayesian methods, could somebody maybe confirm that regularization is actually in some sort of sense comparable to objective Bayesian estimation?).
Comment: I can't see this:"by shrinking the parameters…it will reduce the tendency to fit the random noise" (well… not for my example above!). Missing points could be at either side equally likely, so shrinking the parameters does not guarantee a better fit.   I do understand regularization in the sense of polynomials (polynomial of 2 is simpler than a polynomial of 3) and makes sense for me intuitively. But for this case… why is a slope of 0.9 considered simpler than a slope of 1?? Intuitively this would be: after someone draws a line through some points, to just 'decrease the slope a little bit' why?
Comment: @Chicago1988 I have edited my answer to hopefully make it more intuitive the part about the bias/variance trade-off which was explained more in the other (linked) question.
Comment: I am currently editing the answer using my phone so I can not add a graph that I had in mind, but what you could do is make a plot of the biased error versus the unbiased error, ie $y=(c\hat\beta - \beta)$ as function of $x=(\hat\beta - \beta)$. Then you can see how the improvement or detoriation of the shrinking is as function of the unbiased error. Indeed sometimes you loose, sometimes you win, and those red/blue points in your example show conveniently a win case which is not always occuring, but the net win-loose is positive. On average you make an improvement.
Answer: Consider a large collection of regression problems like this one, with different 'true best' slopes and different estimated slopes.
You're correct that in any single data set, the estimated slope is equally likely to be above or below the truth.
But if you look at the whole collection of problems, the estimated slopes will vary more than the true slopes (because of the added estimation uncertainty), so that the largest estimated slopes will tend to have been overestimated and the smallest estimated slopes will tend to have been underestimated.
Shrinking all the slopes towards zero will make some of them more accurate and some of them less accurate, but you can see how it would make them collectively more accurate in some sense.
You can make this argument precise in a Bayesian sense where the shrinkage comes from a prior distribution over slopes or just from the idea that the problems are exchangeable in some sense.
You can also make it precise in a frequentist sense: it's Stein's Paradox, which Wikipedia covers well: https://en.wikipedia.org/wiki/Stein%27s_example
Comment: I like your answer, but you say that for large collection of regression problems like  this one, if I multiply all the slops for ie 0.9 I will get a better result if I multiply them by 1.1. Since the real slope is equally likely to be above or below I dont see how this could work...
Comment: Have you found an answer that satisfies you @Chicago1988?
Answer: This seems a really interesting discussion and it is maybe nice to point another feature of regularization.
Why regularization reduces the risk of overfitting?
At a first look could sound strange to talk about overfitting for such a simple model (simple linear regression). However, I think the point the example wants to emphasize is the impact of the regularization on the leverage.
Suppose we have a rigde regression (what follows can be generalized to more exotic problems)
$$
\hat{y} = X \hat{\beta} = X (X'X + k I)^{-1} X' = H y
$$
where $H$ is the hat matrix, $X$ is the model matrix ($n \times p$) and $I$ is a regularization matrix shrinking the values of $\beta$. The leverage is equal to the diagonal elements of the matrix $H$ (let's indicate them as $h_{ii}$). This is true for the simple regression model as well as for the regularized one (and for any regularized estimator for what matters). But what is the impact of the regularization on the leverage exactly? If we compute the SVD of $X = UDV'$, can be shown that the ridge leverage is equal to
$$
h_{ii} = \sum_{j = 1}^{p} \frac{\lambda_{j}}{\lambda_{j} + k} u^{2}_{ij}
$$
with $\lambda_{j}$ equal to the $j$th eigenvalue of $X'X$, $u_{ij}\lambda^{1/2}_{j}$ is the proj. of the $i$th row of $X$ onto the $j$th principal axis, and $\mbox{tr}(H) = \sum h_{ii}$ measures the effective degrees of freedom. From the formula above we can deduce that for $k > 0$

For each observation, the ridge regression leverage is smaller w.r.t. the LS leverage
The leverage decreases monotonically as $k$ increases
The rate of decrease of the leverage depends on the position of the single $X$-row (the rows in the direction of the principal axis with larger eigenvalues experience a smaller leverage reduction effect).

Going back to the example, In my opinion, the author just wants to stress the fact that the regularized line is not pulled down by the blue point around 20K as much as the non-regularized one when the red dots in the same surroundings are taken out (this in light of point 1&3 above). This prevents 'overfitting' (wich we can read here as high influence) and ensures better results also for unseen data.
I hope my answer adds something interesting to this nice discussion.
Answer: It's an awkward example to demo regularization.
Why would you regularize a model with two parameters and 36 data points? If anything the issue is underfitting - there's not enough variables (or degrees of freedom) in this model. So, you are right to call the author out on this example.
He has an appropriate overfitting example in the book. Here's the Figure:

Now, if you'd apply regularization and high degree polynomial, then it would be a great way to show how regularization potentially can improve performance of a model, and limitations of regularization.
Here's my replication of the result:

I applied a order 15 polynomial regression of the kind that Excel does, except my $x^k$ were standardized before plugging into the regression. It's the crazy dotted line, similar to one in the book. Also, you can see the straight line regression, which seems to miss that "life satisfaction" - (why would any pick this as an example?!) - saturates. I suppose we should stop trying to satisfy Western consumers at this time, not worth it.
Next, I applied Tikhonov regularization (similar to ridge regression) and show it in green solid line. It seems quite better than the straight polynomial. However, I had to run a few different regularization constants to get a fit this good. Second, and most important point is that it doesn't fix the model issue. If you plug a high enough GDP it blows up. So, regularization is not a magic cure. It can reduce overfitting in interpolation context, but it may not fix the issues in extrapolation context.
That's one reason, in my opinion, why our AI/ML solutions based on deep learning and NN are so data hungry: they are not very good at extrapolating (out of sample is not extrapolation, btw). They don't create new knowledge, they only memorize what we knew before. They all want every corner covered in the input data set, otherwise they tend to produce ridiculous outputs, unexplainable too.
So, this example would have been close to what ML/AI field does in spirit. A univariate linear regression, like in the example you show, is an exactly the opposite in spirit and letter to what ML/AI field uses. A parsimonious explainable trackable model? No way!
A little feature engineering goes long way
Here, instead of using the polynomialregression, I plugged what's called Nelson-Sigel-Svensson model from finance. It's actually based on Gauss-Laguerre
orthogonal functions. The straight fit (dotted line) produces a very good interpolation. However, its value at very low GDPs doesnt make much sense. So I applied a Tikhonov regilarization (green line), and it seems to produce more reasonable fit in both very low and high GDP at expense of poorer fit insde the observed GDP ranges.
Comment: If by colleagues you are hinting at my answer.... I was not trying to rationalise the particular example. With my answer I was trying to rationalise the underlying effect. I agree that the example from that book is not so great (it is indeed not typical for regularisation) and the critical/good student is right to be worried that the particular example appears as just a convenient example that shows one case where it worked. But in that way we do not really answer the underlying question. *Why* regularisation works with slower slopes, and not just in the case with many redundant regressors.
Comment: Aksakai: Do you have the book and know the context? My question under the original posting shows that I agree with you that the example as presented doesn't make much sense, however I was wondering whether there is some background in the book that would bring in some sense, like some formal way of selecting subsets involving some degrees of freedom.
Comment: @Lewian, I do have the book. No, there's no formal way of selecting subsets. I doubt that it's even a method. I think he was trying to show that the rightmost three observations stick out. There are many ways to approach this. For instance, you could try to cluster the observations, apply nonlinear fits, nonparametric, splines, GAM etc.

The problem though is that the model itself is hopeless. No matter what you it's not going to be a useful model because life satisfaction cannot be explained by GDP/capita, it's just a fact of life.
Comment: @SextusEmpiricus my impression was that OP is doubting this particular example and not questioning regularization in general. I think a term *slope* is also unfortunate as it is directional. *sensitivity* is a non directional concept and would be more appropriate in the context of regularization discussion. The latter decreases sensitivity and effectively constrains the degrees of freedom, the concept to understanding of which OP alluded to. I was surprised that there were several answers and none of them seemed to agree with OP that the example was problematic didactally
Comment: My initial thought was to write that regularisation doesn't work for just a simple regression line when there aren't that many regressors. But then when I wanted to write it down and show that there is *no* improvement with regularisation for a single line then I thought, 'wait a minute, this is just like some way to do JS estimation or some other shrinking'.
Answer: I'm going to ignore all rigor and just give an answer that (hopefully) appeals to intuition.
Let's consider least squares. Then our goal seeks to find $argmin\{ RSS + \lambda J \}$ where $J$ is the complexity penalty and $\lambda$ is a tunable hyperparameter. You can think of $J$ being L1 or L2 regularization, maybe $J := \|\beta\|^2$.
So ignoring all equations, let's just think about this problem. Since our goal is to minimize this sum, then it will be small when $RSS$ and $\lambda J$ is small. Well, since $J$ is by definition the norm of the weights vector, it will be small when the weights are small.
Since the weights determine the slope, it follows that regularization will give us a lower slope.
Comment: This is a good answer to a different question. In the body of the question, OP is asking why a lower slope reduces overfitting. I see how the title is misleading though.
Comment: Oops. Misunderstood.


Setting an Expiry date for iPhone app

Question: Currently i am developing one gaming iOS application which i will give to some of my customer for demo.
But while distribution of my app i want to set an expiry mechanism in my app, so that it will get expire after "N" number of days.
It means that (e.g. after 30 days) my app won't work.i can able to this by using system date & time, it means whenever my program starts i check today date and expire date.
The problem is if the user changes system time, my comparison won't be correct.
Also if user delete & reinstall the app,it wont work.
Any help or suggestion?
Comment: You know that demos are not allowed in the App Store, right?
Comment: Apple wouldn't let you do this. Try instead to make a "lite" version that has less features. Many apps do this to let people test it out.
Comment: @DavidRönnqvist , i know that, but this thing i am not going to put into appstore as of now , this is for internal client demo.
Comment: @user1227928 that is not the norm so you should make it more clear in the question. It is an important price of information.
Comment: possible duplicate of [How can I locally detect iPhone clock advancement by a user between app runs?](http://stackoverflow.com/q/7122216)
Answer: Look at Ad Hoc Distribution
Ad-hoc development builds last for 3 months, however if you want to add a time limit then you could:
Add a key-value in NSUserDefaults which stores the start date of the app (time taken from a webservice such as http://www.earthtools.org/webservices.htm#timezone) then every time the app enters the foreground check the time against it and if it is over the threshold then to cancel loading the app.
NSDate *now        = //load current datetime from restkit
NSDate *startDate  = [[NSUserDefaults standardUserDefaults] objectForKey:@"startDate"];
NSDate *futureDate = [NSDate dateWithTimeInterval:60 * 60 * 24 * 30 sinceDate:startDate];

if ([futureDate compare:now] == NSOrderedAscending) {
    //stop the application loading by loading a NIB and displaying a message.
}

I would recommend using RestKit to request data from the web-service.
Comment: just for accuracy: 86400 seconds are not necessarily a day (daylight saving time). while for this task that might not be important, if you want a date EXACTLY in 30 days you date creation with NSDateComponents and NSCalendar instead.
Answer: When the app expires, store something in the Keychain to indicate this fact. Then just check that at startup, rather than the date.
Alternatively, you can have it check a web service you control.
Comment: keychain is an better option than nsuserdefaults, as information stored in it wont get deleted with the app. so with user defaults re-installing would ste back the timer. with keychain that wont happen.

Setting an Expiry date for iPhone app


Random effect in GAM (mgcv package)

Question: I am using the mgcv package in R to model the ratio of damaged culture hectares by wild boar in each french department according to some environmental covariates. I used a using a Beta distribution for the response.
For each department, the damages are estimated in 3 different culture types (« Culture »).
Also, the department are clustered into landscape types (« Cluster »).
Since I wanted to get the effect of the Culture type and the Landscape, I keep those variables as fixed effects in the model.
Also, since we have 5 repetitions in time of the response and of some covariates measurement per department and culture type, I put a random effect on the Department per Culture type and put the year as fixed effect as well.
The model takes the form :
gam_tot <-gam(resp  ~ Culture + Cluster:Culture +
                        s(Year,k=4, by=Culture) +
                        s(X1, by=Culture) +
                        s(X2, by=Culture)  +
                        s(Depts, bs="re", by=Culture),
                        family=betar(link="logit"), method="REML",
                        data=data, select=FALSE)

Then, I estimated the part of the model explained deviance provided by each covariate. For that, I run the model without the given covariate (keeping smooth parameters constant between models), and compute the difference in deviance between the Full model (with the given covariate) and the penalized model (without the given covariate):
(Full model Deviance – Penalized model Deviance) / Full Model Deviance
From that, I get a huge proportion of Deviance explained by the random effect (Department) of about 30 %, while the others covariates explained less than 1 %.
At this point, I have few questions :

Do you think my model formula is correct regarding my data and questions ?
Is my estimate of explained deviance correct ?
In that case, how can I explain such a discrepancy between the part of explained deviance by random and fixed effects ?
Answer: When you do a by-variable smooth, you are allowing for different smoothness parameters for each level of Culture. This is a more complex assumption than just simple nested random effects. Do you expect Depts to have different variances for each Culture?
I would start with s(Depts, Culture, bs = "re") or, if that isn't quite what you want, s(Dept, bs="re", by=Culture, id = 0) (the id = 0 is there to give all Cultures the same smoothness parameter).
You don't have a Cluster main effect in the model, which is going to make the Cluster:Culture term difficult to interpret.
I'm not 100% sure you need Culture as a main effect (or interaction); typically this is needed because by variable smoother are centred due to the identifiability constraints. You already have Culture accounted for in the random effect spline. I don't see that you need both.
I can well believe the random effect explains a huge amount of deviance — it is taking care of all the between Depts and between Culture variance. The other terms are accounting for within cluster variation. Whilst it won't consider the fixed effect categorical terms, you could use gam.vcomp() on your fitted model to turn all the smooths into mixed model variance components, which would show you the amount of between and within variation explained by the s() terms.
Comment: Hello, thanks for your answer.

In this study we really want the effects (estimates) of each covariate for each Culture type. Also, I have put the Culture systematicaly in interactions with covariates. It is an a priori that constrains  model formula.

I will investigate the interaction with id=0, but I guess that the response is constrained to have the same shape in each block (Culture) then, is that it ?

Many thanks

Amélie
Comment: Right, but your formula still needs to include `Cluster` as a *main* effect: `Culture + Cluster + Cluster:Culture`. `id = 0` doesn't make each spline have the same shape, but they should have the same wiggliness.
Comment: Hello, I have run gam.vcomp but, regarding the sdandart deviation estimated for each smooth, I get different importance of each smooth than with the model comparison based on explained deviance (as explained in my first post). In particular, the random effect has a smaller standart deviation than others smoothed... Could you explained me where that could come from? I thought that the standart deviation was an estimate of the deviance...

Random effect in GAM (mgcv package)


domain of convergence of power series

Question: I need to find radius of convergences and domain of convergence for the:
$\sum_{n=1}^{\infty}3^{n^{2}}x^{n^{2}}$.
Can you help me please?
Comment: You may wish to write the general term as $ \ (3x)^{n^2} \ $ .  This looks like a job for ... the Ratio Test!
Comment: Have you tried anything? Why didn't it work? You do remember the result stating that for a series to converge, the general term should $\to0$. Have you checked for which $x$ does that happen?
Comment: Please let us know what are your opinions on the problem, what have you tried?
Comment: I tried to find radius and got:$ R=\frac{1}{\lim \sqrt[n]{3^{n^{2}}}}=0$
Answer: Using the Cauchy test
$$\lim_{n\to\infty}\sqrt[n]{|3x|^{n^2}}=\lim_{n\to\infty}{|3x|^{n}}<1\iff|x|<\frac{1}{3}$$
so the radius of convergence $R=\frac{1}{3}$ and it's clear that the series is divergent for $x=\pm \frac{1}{3}$ hence the domain of convergence is the interval $(-\frac{1}{3},\frac{1}{3})$.
Comment: Maybe he want the domain of convergence in the complex plane?  He didn't say.
Comment: @Sami Ben Romdhane Thank you. I tried to find the radius and got that: $R=\frac{1}{\lim \sqrt[n]{3^{n^{2}}}}=0$.. Why is it wrong?

domain of convergence of power series


what if I lost the keystore which generate the CSR

Question: Sorry I am a beginner about ssl cert.
according to
http://tomcat.apache.org/tomcat-7.0-doc/ssl-howto.html#Create_a_local_Certificate_Signing_Request_(CSR)

it will gen a keystore and CSR.
we generate the CSR and send to Certificate Authority.
What if I lost the keystore ? should I regen the CSR again to reapply the ssl cert?
Refer to
https://search.thawte.com/support/ssl-digital-certificates/index?page=content&id=SO832
It will generate a new keystore file.
is it the file store the private key? which stated in https://search.thawte.com/support/ssl-digital-certificates/index?page=content&id=SO750
, which say
1. Private Key file loss.

2. Private Key pass phrase loss.

3. Private Key file has been compromised due to the server being hacked.
......
......

Answer: Yeah, if you've lost the keystore then you've lost the private key.
The certificate generated from that CSR is now unusable to you, but the certificate authority should happily re-issue a new certificate if you generate a new CSR from a new private key.


Why is vii0 so rarely used, but V 6/5 commonplace?

Question: vii0 (5/3, vii06 is more common) is almost never used in functional harmony, the reasoning being that the diminished chord creates a tritone against the bass. But V6/5, a far more common chord, has the same tritone, and is virtually the same chord. Why would vii0 be so rarely used because of the tritone, while V6/5 has the same tritone but is still used commonly?
Answer: While this may be asking for an opinion, the predominance of V65 vs vii0 is pretty large. The root position vii0 seems to have been avoided by most composers from the Renaissance on, the vii06 was a common substitute. I'm guessing that the tritone is "interior" rather than against the base for this case.
The V65 does have a tritone against the bass though. Various theorists (Piston is one) did claim that many composers, especially from the Nineteenth Century, treated the vii07, and its minor form (I don't have a phi) were often treated as a dominant seventh with the root missing. The only place vii0 was used as itself was in sequences (preceding the iii chord in a major key.)
While the vii0 and the V65 only differ in that the V65 has a sounding scale step 5 (no carets for numerals either, not even in Unicode). Perhaps the combination of avoiding vii0 in general and having the putative root sound made the V65 more useful. (Or at least better sounding to composers.)
Comment: what is "minor form of vii07"?
Comment: @user1079505 - Based on the "I don't have a phi" remark, I assume the "minor form of vii07" is actually vii half-diminished 7th.
Comment: That's the problem. I don't have a website so I cannot connect to pictures. Perhaps sometime in the future. I'd still like to have a "music" font  (even the text part.) My point was that the V65 contains the root and that vii0 wasn't popular even in pre-chordal days; vii6 was though (the dissonant interval was not sounding against the bass but this idea doesn't directly apply to the V65.)


How to put two form elements in a row using Drupal Form API?

Question: I am creating a form in Drupal 6 using form API.
I need to put a textfield and a select next to each other. they are for entering something like 'www.domainname.com' . www. is fixed. domainname section is given from user in a textfield and .com section is chosen from select element by user.
So they should be in a line. but as I see I can put these two form elements in a line, they are in their div container.
Would you help me? Thank you.
Answer: This is a CSS issue. All you need to do is limiting the width of both elements and then float them to the left; this will make them inline. Be sure to wrap them both in a div with the "clearfix" class to clear the float.


Serializing a complex object with BinaryFormatter

Question: I am trying to serialize a complex object which contains 2 lists of complex objects using the code below
public static byte[] SerializeObject(object obj)
{
    BinaryFormatter formatter = new BinaryFormatter();
    MemoryStream stream = new MemoryStream();
    formatter.Serialize(stream, obj);
    return stream.ToArray();
}

When I deserialize though I get NHibernate exceptions that my list objects failed to initialize, so I suspect that they haven't been serialized correctly in the first place. The error I receive is failure to lazily initialize a collection of some object, no session or session was closed.
But if they were properly serialized then there would not be a need to lazily initialize, they would already be there, right?
Answer: What may be happening here is that you are serializing NHibernate proxies for the collections.  Depending on your mapping, for performance reasons, NHibernate will not load a collection up until the point you explicitly access its elements.
It's also able to do this for associations of various kinds (it's called 'lazy loading') and the way it works is that NHibernate actually instantiates and uses a proxy object that implements the correct interface (or derives from your classes in case of other associations).
You may already know all that, but I'm explaining it for context in case you don't.
If you need to know more about lazy loading check out this article: http://nhibernate.info/doc/howto/various/lazy-loading-eager-loading.html
In this case, NHibernate may be using a proxy for your lists and as the BinaryFormatter is accessing them in a non-conventional way that is what you end up serializing.
If this is the case, there are many ways in which you could go ahead and fix it and they depend on how you are structuring your project.
A quick way to confirm if this takes care of your issues is, before serializing your object go ahead and initialize its lazy properties (note that you need to do this for each one or recursively as the Initialize method will only load data for the proxy you give to it):
NHibernateUtil.Initialize(yourObject);
NHibernateUtil.Initialize(yourObject.List1);
NHibernateUtil.Initialize(yourObject.OtherList);
...etc...
SerializeObject(yourObject);

Comment: AVOID supporting runtime serialization or XML serialization just for general persistence reasons. Prefer data contract serialization instead [link](https://msdn.microsoft.com/en-us/library/6exf3h2k%28v=vs.110%29.aspx)
Comment: You were right. On a different note, I read on msdn that the Serialize attribute should not be used for general purpose serialization, instead use the DataContract ones. What is your view on this?
Comment: I have only ever used DataContract on the context of WCF serializing, where I've done so exclusively. For general purpose serializing (like serializing for storing into the database) I still stick with the classic attribute and implementation, if required. But the truth is that I don't have any insights as to why, so I would be interested in seeing a link to the msdn article/discussion you mention.


Add prefix and suffix to all occurrences of a word in a string in JavaScript

Question: I have a text file which I can read as a string for example something like this...

Hello This is a test string this is a test THIS is just a test ok? Can we solve This? Idk, maybe thiS, is just impossible.

I want the output to append "Foo" to the front and "Bar" to the back of every "this" word (case insensitive) so that the output will look like this:

Hello FooThisBar is a test string FoothisBar is a test FooTHISBar is just a test ok? Can we solve FooThisBar? Idk, maybe FoothiSBar, is just impossible.
Comment: Can you share your attempt at solving this problem? Then we can help you to fix it.
Comment: Is this just a riddle or do you want to do "serious" language processing? Is search "this" case insenstive and add bar o.k.? Or i.e. must this be a separate word and do not exist within another word etc.
Answer: Regex
Match every occurence of "this"
Simple replace with a capturing group:

const str = "Hello This is a test string this is a test THIS is just a test ok? Can we solve This? Idk, maybe thiS, is just impossible.";

const result = str.replace(/(this)/gi, "Foo$1Bar")
console.log(result)

Only match "this" when it is a word (works with punctuation)
To avoid matching "this" inside a word (e.g, "abcthisdef"), you can use a negative lookahead and negative lookbehind:

const str = "Hello This is a test string this is a test THIS is just a test ok? Can we solve This? Idk, maybe thiS, is just impossible.";

const result = str.replace(/(?<!\w)(this)(?!\w)/gi, "Foo$1Bar")
console.log(result)

Non-regex
You can split the string by a space, map through the resulting array and return the modified string only when the item (when converted to lowercase) is equal to "this":

const str = "Hello This is a test string this is a test THIS is just a test ok? Can we solve This? Idk, maybe thiS, is just impossible.";

const result = str.split(" ").map(e => e.toLowerCase() == "this" ? `Foo${e}Bar` : e).join(' ')
console.log(result)

The caveat with the above solution is that it will not match "this" when it is beside punctuation. E.g, it will not match "this.".
To also replace words with trailing punctuation, you can first split the string with a regex that matches non-alphanumeric words, check whether the first item is "this", then concatenate the second item after (after first joining, since the second item in the destructure assignment is an array of trailing punctuation characters):

const str = "Hello This is a test string this is a test THIS is just a test ok? Can we solve This? Idk, maybe thiS, is just impossible. this??? this!";

const result = str.split(" ").map(e => {
  let [word, ...punctuation] = e.split(/(?!\w)/g)
  return word.toLowerCase() == "this" ? `Foo${word}Bar${punctuation.join('')}` : e
}).join(' ')
console.log(result)

Note that this solution will not work if there is punctuation before the occurence. For example, it will convert "this" to this". To avoid this, use the recommended regex solution above.
Comment: Let us [continue this discussion in chat](https://chat.stackoverflow.com/rooms/238038/discussion-between-spectric-and-pedram).


$y=f(x)$ and $y=g(x)$

Question: I understand the phrase $y=f(x)$ to mean $y$ is assigned the value of $f$ evaluated at each point $x$, when we have two functions we might write $y=f(x)$ and $y=g(x)$ for some functions $f, g$. Now we can evaluate the functions at some point, lets say $x=1$ to give $y=f(1)$ and $y=g(1)$ however its not neccesary for $f(1) = g(1)$ (think of any two functions who do not agree at $x=1$), so we cannot write $y = f(1) = g(1)$ as $y$ appears to take two different values (namely $f(1)$ and $g(1)$). Could someone try explain my misunderstanding to me please? I am high-school aged. EDIT I have made sense of the problem like this, we have been using $x$ as a variable for so long and never question why $x$ takes different values because we know its value isnt fixed, so the same is true for $y$....)
Comment: I have seen plenty of times a question which asks, "Plot $y=x^2$ and $y=x$ on the same coordinate axis" for example.
Comment: I think its dodgy because, if $y=g(x) = f(x)$ this only holds if $x$ is a point of intersection of the graphs, or if $f=g$ for all $x$, In general after substituting $x$ for an element of the domain of both functions we get two values for $y$ but we know $y$ cannot be two things at once.....
Comment: The question posted as " Misleading function notation" only furthers my confusion,
Comment: If $f(x)$ and $g(x)$ are different functions, DON'T write $y=f(x)$ and $y=g(x)$ inside the same discussion ... for example, use different letters $y=f(x)$ and $z=g(x)$.
Comment: Yes, the answers in that linked question don't say what is important. The thing is that when one writes "... the functions/graphs $y=f(x)$ and $y=g(x)$", it should be understood as $f=\{(x,y)\in\mathbb{R}^2\mid y=f(x)\}$ and $g=\{(x,y)\in\mathbb{R}^2\mid y=g(x)\}$. The variables are bound. Their scope is withing the definition of the graph/function being talked about. The $x$ and $y$ in the first are in a different scope as those in the second. They are different variables.
Comment: This is what my answer in the linked question actually says @NDB
Comment: I see, like when I write $y= g(1)$ I am saying that the graph of $g$ passes through $(1,g(1))$, $g(1) = y$ has nothing to do with the $y$ in the definition of $f(x)$, you see?
Comment: @nicomezi No mention of scopes, or bound variables.
Comment: When I see people writing $y_1$ and $y_2$ it makes a lot more sense but it is not standard notation, is that because most people don't worry about this issue much?
Comment: I have simply phrased these concepts differently.  I am not sure that an extended discussion on these concepts shed more light here. @NDB
Comment: @NavBhatthal Yes, like in many languages, people agree to understand some ideas that are not explicitly said. Things get omitted. If someone doesn't understand, they ask for clarification, and that's it.
Comment: Thanks NDB for your help
Answer: It's just the result of using abbreviated notation.
When you say "Plot the graph $y=x^2$", what you really mean is "Plot the set of points $\{(x,y)\in \mathbb R^2 : y = x^2\}$". The $x$ and the $y$ are dummy variables used to show the relationship between the coordinates of the typical point on the graph of that function. They have absolutely no meaning outside of the set notation in which they are used.
So it it perfectly reasonable to say "Plot the two sets of points $\{(x,y)\in \mathbb R^2 : y = f(x)\}$ and $\{(x,y)\in \mathbb R^2 : y = g(x)\}$" because the variables $x$ and $y$ are only used within the set notation to describe the points in the set.
The corresponding "abbreviated" phraseology would be to say "Plot the two graphs $y=f(x)$ and $y=g(x)$". Knowing what is really meant by these removes any confusion.
Comment: You are the first person to tell me about the idea that $y$ is not the same in both definitions but rather a place-holder, and now that I have embraced your idea the confusion is wearing away. Everyone else online told me that the $y's'$ are the same and it was very very confusing to say the least. Thanks!
Comment: @NavBhatthal Read about *bound variables*, in particular the case of [variables bound in function expressions](https://en.wikipedia.org/wiki/Free_variables_and_bound_variables#Function_expressions). Also read about the [scope of variables](https://math.stackexchange.com/q/610967/1198684)
Comment: How do we get around the issue of having $y$ $=$ to two different values at once?
Comment: @NavBhatthal : But it isn't true that $y$ equals two different values at once. $y$ is a placeholder that allows you to speak of the generic point instead of having to speak of each specific point individually. Instead of having to say "$4=2^2$ and $9=3^2$ and $100=(-10)^2$ and $\frac14=\left(\frac12\right)^2$ and...", you can indicate the generic relationship by saying "$y=x^2$ for each point $(x,y)$ on the graph", or more briefly, just "$y=x^2$" with it being understood that the relationship is meant to hold for precisely the points on the graph.
Comment: @NavBhatthal : And then you can also say, that **if** $x=2$, **then** $y=4$ (understanding the context $y=x^2$ for points on the graph).
Comment: I am saying that when graphing $f$ and $g$ on cartesian $xy$ grid, for some value of $x$, say $x_i$ we have two (or more if the functions are not well-defined) values of $y$, namely $f(x_i), g(x_i)$, does that not mean we have two values of $y$? IF $x = x_i$ then $y=f(x_i)$ AND $y=g(x_i)$.
Comment: Refer to the third paragraph of my answer. In that case, your $y$ can only have meaning when being used in the description of ONE graph. When you speak of the OTHER graph, you are using the dummy variable in a different context. They are NOT the same variable.
Comment: Thanks NBD, do you know why in the last $5$ or so years of me learning mathematics at highschool level I have never heard anyone mention scope or bound variables? Is it taught later on, or just assumed that its obvious?
Comment: @NavBhatthal Same as when toddlers don't learn to speak by learning grammar first. Instead some rules are learned by imitation and being corrected if they say something wrong.
Comment: That makes me slightly embarrassed to have asked this question.
Comment: @NavBhatthal : No reason for embarrassment. You asked what many many others didn't understand but were afraid to ask. They should thank you.
Comment: One last thing, in my example where I used $x_i$ is it better to write, for $f$ when $x = x_i$, $y = f(x_i)$, then the same for $g$? Rather than writing $y= f(x_i)$ AND $g(x_i)$?
Comment: @NavBhatthal : If you're really talking about specific values of $x$ and/or $y$, you can distinguish them with subscripts or various decorations. For example, if you are evaluating functions $f$, $g$, and $h$ at the points $x_1$ and $x_2$, you could use (say) $y_i = f(x_i)$, and $\hat{y}_i = g(x_i)$, and $\dot{y}_i=h(x_i)$.
Comment: But my method is better than saying AND right? Thats what I want clarification on, thanks

$y=f(x)$ and $y=g(x)$


Lync Certificates

Question: I have been struggling trying to figure out the right way to do this.
Here is my setup. I have 2 sangoma servers (Lync 2013 in a box) The Front End server is is the main server. The Reverse Proxy and Edge Servers are VMs on the Front End.
LyncFE1 I go through the Deployment Wizard and I see I have 2 internal interfaces that have internal CA Certs. All good. Then I have one external interface with the godaddy cert.
Edge1 I go through the Deployment wizard I have one internal and one external interface each with the appropriate certs.
Reverse Proxy 1 I use IIS and it has the right Cert.
Then I go to
LyncFE2 and all 3 interfaces I have the internal Cert.

I had a vendor who installed this and we are ironing out the issues but they are gone and I need to renew the godaddy. I have followed the steps of building a request (Checking all private keys to be exportable) and pasting it on godaddy's site and getting the IIS version of the certs. But when I go import the cert I does not show up in the assignable cert. So I tried going through certmagr and It installs again it is not available to assign and If I try to export it I do not get the option to export the Private keys.
I built the request on the FE and installed on the FE. Should I be building the request on the Edge? Should I be downloading a different version like exchange? What am I doing wrong? Shouldn't LyncFE2 have the godaddy cert?
Comment: "The Front End server is is the main server. The Reverse Proxy and Edge Servers are VMs on the Front End." This is just wrong on so many levels...
Comment: Anyway, you seem to have *four* servers: two front-ends, one edge and one reverse proxy. And yes, if you have two front-end servers in the same pool, they should use the same certificates for the same roles.
Comment: But they could happily use private certificates for the external web services: the reverse proxy is the only server which is actually Internet-facing, thus you could put the public certificate there and use private certificates on the actual servers; the RP will proxy the requests to the internal servers, and external clients will only see the certificate on the RP.
Answer: I did get it work I had to create the request on the Edge server and now I have both FEs using the same certificate. I used the godaddy cert because I could basically. Thanks for the information Massimo. Since that vendor left me high dry on some stuff I am learning a lot.

Lync Certificates


Will my wind instrument be damaged if I leave it assembled?

Question: Almost every teacher, expert, and book has informed me that I should disassemble my (clarinet / recorder / saxophone) each time after I practice.
However, it is difficult for me to see how this would prevent damage to the instrument, after I regularly grease the cork in the fittings, swab out the moisture, and remove the reed.
On the other hand, although it may seem trivial, I am much more likely to practice if my instrument is assembled than if it is in the case.
What is the basis for the advice that an instrument should be disassembled?
Answer: As long as you are following good maintenance practices, then no, the only added risk of damage comes from the instrument not being in a protective case. (Hopefully the instrument isn't sitting on a stand long enough for it to collect dust.)
Of course, on a clarinet, part of good maintenance practice is swabbing out the moisture after every playing session, and many clarinetists do this separately for each joint so they don't miss any moisture collecting near the corks. Leaving a reed on the mouthpiece for extended periods of time will get you a moldy mouthpiece. But as long as you are properly caring for the instrument and not putting it in harm's way, then leaving it assembled should be fine.
The reason most teaching resources recommend that one puts away their instrument back into the case is that it's far too easy to not follow good maintenance practices. The simple act of, say, taking your mouthpiece out of your trumpet after you play helps to ensures that the mouthpiece isn't going to get stuck in.
Similarly, if you do decide to leave your clarinet out of the case for extended periods of time, every few days you should give it a quick once-over to polish any dust off and make sure all of the corks/joints move satisfactorily.
Comment: +1 for maintenance procedures - this is undoubtedly why many teachers hammer the after-practice routine when they get a starting student. Taking care of your instrument is extremely important, but easy to neglect.
Answer: For me then putting my flute away involves me cleaning it out (removing the moisture). If I leave it out then I don't do this, because you need to dissemble a flute to clean it. And if I am cleaning it, therefore dissembling it, then why not put it away...
But if you're doing as you say, taking care of your instrument, then I see no reason to put it away. As long as you're careful not to knock it over, etc (it can happen so easily) then you'll be fine.
Comment: @David The transverse C flute has 3 sections: Headjoint, body and footjoint. Basic cleaning of the flute involves separating the three sections and running a cloth through them, and wiping down the outside.
Comment: Is it only required to remove the mouthpiece on a flute? Otherwise, why is taking the entire instrument apart required?
Answer: Taking apart the instrument and putting it in the case lessens the probability of someone knocking off a table...or tripping over it on a floor stand...or playing with it...you get the picture. Also, in the case of wooden instruments, placing it in a case with a hydration device will help prevent the wood from drying out and cracking.
When I finish practicing my flute (scheduled practice), I take it apart, clean it, and then put it back together and leave it on the desk since I am the only one using that room. I often pick it up and play a bit at random times. I nearly always put my trumpet back in its case, though, since it's easy to drop the mouthpiece in and take it out of the horn.
Comment: +1: Excellent point about wood instruments. Hopefully OP isn't practicing in a meat freezer.
Comment: Putting away your instrument is also good advice for a string instrument, especially in wood.

They do not need to be disassembled, most of the time (except sometimes shoulder-rest that do not fit in the case), but they are better off in a case, without dirt, with slowly varying humidity (for all parts), without light (for the varnish), in company of their bow (which is fragile, can spread rosin on cloths and furnitures and should not be left alone).

Also most accidents I have seen for pupils' instruments involved it just a few minutes before being put on a chair or on a bed.
Answer: I put my clarinet on a stand I made out of plywood, a steel plate, and a wooden rod. Mouthpiece, ligature, and reed go in the case. I clean thoroughly after playing, then re-assemble it and put it on the stand. It smells better than it did in the case, and I like fingering on it, even without sound. I practice 4 times a week and no dust builds, ever. Works for me. Make sure the clarinet is cleaned, stored upright on a study stand, and played often, and you'll have no problems with damage.
Comment: Your method also means that there are seven hundred and thirty fewer wrestlings with the joints ( and the accompanying risk of key damage) in an average year.
Answer: In addition to the other answers, the cork joints of some instruments (clarinets, most recorders, sax mouthpiece, etc) get compressed and with time need to be replaced.  This will happen less often if you take the joint apart so the cork can expand between playings.
Answer: I left my clarinet out of its case for a few days, intending to continue learning it next day. What a shock when I saw that all the metal bits had become tarnished! Lesson learned.


Solving a system of equations with summation

Question: How to solve these equations with respect to $x$ and $y$: $$\underset{i=1}{\overset{n}{ \sum  }}\left(b_i \left(a_i+b_ix+c_i y\right)\right)=0\land \underset{i=1}{\overset{n}{ \sum  }}\left(c_i \left(a_i+b_ix+c_i y\right)\right)=0$$
$a_i$, $b_i$, $c_i$, $x$ and $y$ are reals, and there is exactly one solution! (I think that is the same as n>1, and probably some more).
Answer: Is a $2\times 2$ system:
$$\left(\sum b_ia_i\right)+\left(\sum b_i^2\right)x+\left(\sum b_ic_i\right)y=0$$
$$\left(\sum c_ia_i\right)+\left(\sum c_ib_i\right)x+\left(\sum c_i^2\right)y=0$$
BTW, if $b_i=c_i$ for all $i$, does not have unique solution.


Create new pipeline for TFS on visualstudio.com

Question: When I try to create a new pipeline in visualstudio.com, I don't see the option to get sources from TFS, only from GIT. There is a message saying:
"To create a pipeline for TFVC, BitBucket, or use the old designer, disable the "New YAML pipeline creation experience" preview feature"
Where can I disable the "New YAML pipeline creation experience"?
Answer:
From your account, Click the preview features

Change the preview features from for me to for this account/organization

Disable the Build YAML Pipelines

Reference
Comment: Perfectly explained! Thanks so much!


Is it usual to have no intuition to certain proofs and simply do them mechanically?

Question: At least two books I have read, claim that proofs are not supposed to be intuitive and are meant to be terse and mechanical. I find this confusing as mathematicians are humans too. Differential geometry once upon a time was seen as simply a theoretical mathematical concept which had no real world applications. Einstein proved this wrong by using differential geometry in his theory which actually implies that Euclidean geometry is an approximation and differential geometry is more accurate for our world. Doesn't this say that Einstein could just 'feel' the way the world was non - Euclidean?
Differential geometry may seem hostile at times but if one is to translate those mysterious proofs and mechanisms to real world situations, surely Einstein could just speak mathematics as if it were German to him? When we are proving theorems on rings, fields and number systems, the proofs all materialise mysteriously and we are at times satisfied with the way they are non-intuitive. Satisfied simply because we can recall the entire proof and have a logical flow as well. Logical flow will do when we are studying the proof. But didn't someone actually come up with the proof? That person too must have had his 'Eureka' moment when he suddenly notices something that immediately gives him an idea how to prove something.
Comment: Whether something is intuitive depends greatly on your background...
Comment: My short answer is NO. Good proofs provide motivation as well as rigor. I'm sure some readers here will step up with examples.
Comment: Answer to the title: YES.
Comment: To continue on @user251257's comment, things become more intuitive the more you work with them. When learning a proof for the first time, things might seem like magic, but after seeing similar proofs and digesting them fully, similar kinds of questions feel more intuitive.
Comment: I would say it depends on the purpose. To convince people that a mathematical theorem is true, a terse proof suffices. But for any text trying to teach how to think about a subject, a longer 'less efficient' proof would be more instructive.
Comment: Terry Tao's blog post "[There's more to mathematics than rigour and proofs](https://terrytao.wordpress.com/career-advice/there%E2%80%99s-more-to-mathematics-than-rigour-and-proofs/)" is somewhat relevant to this. He talks about three stages of mathematical education: "pre-rigorous", "rigorous", and "post-rigorous". One must pass through the "rigorous" stage, which is roughly what your question is complaining about, to arrive at the "post-rigorous" stage, where one's intuition, grounded in rigor and honed by practice, is actually useful.
Comment: "At least two books I have read, claim that proofs are not supposed to be intuitive and are meant to be terse and mechanical." Which books? I can't imagine authors saying this.
Comment: @zhw. Pinter's  'A book of set theory' and I can even Gauss saying so. He obviously had intuition for his proofs but took great pleasure in removing any way to trace his steps back thus  presenting a very terse proof.
Answer: According to my knowledge and experience, sometimes proofs are more intuitive or clear and less technical, sometimes conversely.
To balance the opinions from books your read I present two others:
Nicolas Bourbaki: "the mathematician does not work like a machine, nor as the workingman on a moving belt; we can not over-emphasize the fundamental role played in his research by a special intuition, which is not the popular sense-intuition, but rather a kind of direct divination (ahead of all reasoning) of the normal behavior, which he seems to have the right to expect of mathematical beings, with whom a long acquaintance has made him as familiar as with the beings of the real world"
Henri Poincaré wrote a paper "Mathematical Creation". You may also look at his paper "Intuition and Logic in Mathematics" (for instance, in this book).
PS. A few of my old answers to similar MSE questions:

Question about long proofs?
How are long proofs "planned"?
Big list of "guided discovery" books
Answer: To quote Spivak from his preface to 'Calculus':

...precision and rigour are neither deterrents to intuition nor ends in themselves, but the natural medium in which to formulate and think of mathematical questions.

But the question may arise why take one author's words and disregard another's. Quite simply because saying things like proofs are 'supposed' to be non-intuitive is not true in any way. Not only is it untrue but it also confuses and discourages amateur mathematicians.
To an uninformed person, Einstein's field equations are nothing more than a bunch of Greek letters put together. If that person asks what those symbols actually mean, he will get explanations about how the world really is non-Euclidean and about the 4th dimension and whatnot. It may seem terse, unapproachable and even false. Even a trained physicist may accept the equation but he or she may not agree that it is intuitive.
But when one hears of the way Einstein himself got his idea. The way he was staring at everyday objects and thinking of them in different situations; thought experiments as they were called. The way he just let his imagination loose like a child, but a mathematically inclined one. The little ideas were so simple that when one hears of them he will immediately connect with them. (Although the mathematics behind them will seem intuitive only to a handful)
Every proof you see, I guarantee you, has intuition behind it. If it seems like a bunch of symbols strewn here and there it is one's incompetency to understand the language clearly.
Whether what is intuitive to one is intuitive to another or not is a different story. But one thing is certain; the more you explore, the more you think, the more thought experiments you conduct, the more mistakes you make...you have a higher chance to connect with the most impenetrable proofs
Answer: To extend the comments above, I think this also very much is a reflection of the idiosyncratic manner in which people learn.  I personally find that 'intuition' for me almost exclusively takes the form of visual insight of some sort into a problem.  I know many people who operate precisely in the opposite way though and who find algebraic/mechanical manipulations the most insightful.  When I read their proofs, it seems like black magic of some sort at first pass.  What may appear terse and mechanical to you in these cases may be very intuitive to someone with the familiarity with the relevant tools, especially if you're at all like me.
Alternatively though, the kernel of the idea behind many proofs is often geometric or visual in nature, and a toolbox with only the more mechanical methods may take longer to arrive at the same place as someone more geared toward visual thinking.
Answer: I guess I'd make the following points:

While it may be usual to have no intuition, it's definitely not ideal! I find that proofs are often mysterious or inexplicable to begin with. Intuition comes with time and thought. Intuition is extremely valuable because it suggests a way forward, a direction to check. Simply understanding the truth of individual steps of a proof is unsatisfying, and doesn't allow you to see the totality of the proof, the overarching story of why something is true. I don't consider myself to have understood a proof until I have some kind of intuition. But getting this kind of intuition is hard and takes a lot of time. However it's time well spent because you will see things that others can't.
Maybe this isn't the case everywhere, but I have always been able to eventually find an intuition for proofs. Sometimes an idea in mathematics is quite bizarre and outside the real of ideas that you would encounter in ordinary life. Intuitions might resemble something like "Loosely, more X seems to generate more Y in this system" or "This kind of structure A seems to frequently appear frequently in situations B". Terry Tao for instance always tries to introduce his intuition on a subject in lectures, even with something as abstract as real analysis. His lectures were the ones that leveraged intuition the most out of all subjects I've ever taken, and I think there are good reasons for that.
Sometimes when a subject is new, the proof and results are extremely unintuitive. People are more concentrated on just proving the result than trying to make how they proved it understandable to someone else (there's also the issue of page limits). But over time, the newer presentations of the same subject matter make more and more sense and are baffling no longer.

In summary, having a low-level understanding of proofs is not only unsatisfying, but makes it extremely difficult to advance your research.
Answer: First,no proofs on any topic are done mechanically without any motivation
WHY:Mathematical Proofs are nothing but paintings on canvas.Ever seen an artist just gazing on the blank paper on his canvas to find out where to start his drawing from.
Just like that! Without any motivation it is hard to come up with a proof of any mathematical phenomenon example theorems,lemmas,etc.
Maybe when we see the whole proof of the theorem,it makes us feel how does one on earth come up with such a beautiful proof.
Secondly theorems do not come out from the hat just like that.You are feeling they are not intuitive because in a book it is just not possible to give every detail of how the proof came up.A book is just organized to include the theorems and its proofs otherwise you would end with a book with $1000-1200$ pages which does not make sense.
Just imagine it took many years to ultimately come to the definition of a GROUP in Abstract Algebra but when we read it in any book of Abstract Algebra,we find everything is so organized and properly given.If it were to include all the details it would never end.
You can just google in to find out more about GROUPS.
And Lastly if you see a complete picture  on the canvas can you just figure out by seeing it that from where did the artist start painting it from?


Divisibility, many unknowns

Question: As I was solving a math problem, I stumbled upon a question:
What conditions must $a,b,c,d,e$ meet for $n$ to be a natural number?
(Frankly speaking, I would like all but one of $a,b,c,d,e$ to be equal to $1$, but I do not know how to prove it.)
Here it is:
$$n=\frac{bcde+cde+de+e+1}{abcde-1}$$
Comment: You cannot have everything equal to 1, because everything equal to 2 is a solution.
Comment: I am sorry for this imprecision. The trick is , n>1.
Comment: If this is the "trick", could you put this "trick" in the formulation of the question?
Answer: Note that if we denote your expression $f(a,b,c,d,e)$ then
$$an=\frac{abcde+acde+ade+ae+a}{abcde-1}= 1+\frac{acde+ade+ae+a+1}{abcde-1}
=1+f(b,c,d,e,a)$$
When $a=1$ the expression decreases by 1, when $a$ is at least 2, the expression increases at least by $a-2$. The same argument holds for the other letters.
If one of the letters is 2, the expression is reduced to only four variables (note that the integrality of all cyclic shifts is equivalent).
So, now you can try $(6,1,1,1,1)$, $(5,1,1,1,1)$, $(4,1,1,1,1)$, $(3,1,1,1,1)$, $(3,3,1,1,1)$, $(3,1,3,1,1)$, $(5,1,1,1)$,$(4,1,1,1)$,$(3,1,1,1)$,$(3,3,1,1)$,$(3,1,3,1)$, $(4,1,1)$,$(3,1,1)$,$(3,1)$.
For every solution you find, you can insert an appropriate number of twos, including the solution with only twos.
For example, you check that $(3,1)$ has indeed the property that $\frac{3+1}{1\cdot 3-1}$ is integral, therefore $(3,1,2,2,2)$, $(1,2,2,2,3)$, $(3,2,1,2,2)$, etc are solutions of the original equation.
Comment: Thank you. It is really helpful. However, I don't know what (5,1,1,1),(4,1,1,1)...(3,1,1),(3,1) mean. There are 5 variables, aren't there?
Comment: "you can insert an appropriate number of twos"
Comment: Ah, right, indeed.

Divisibility, many unknowns


Does the inverse of this function exist?

Question: $r(x)=\frac{2x}{1+x^2}$
So I know that the range is $[-1,1]$, and the function is injective. It is surjective as well in the range $[-1,1]$.
I'm trying to show whether this function has an inverse. Up till now I should be able to show that the inverse exists since $r(x)$ is bijective.
However, after solving for the inverse I got $r^{-1}(x)=1\pm\sqrt{1-y^2}$, which is a circle, I got a bit confused whether this inverse of $r(x)$ exists or not. Surely I did something wrong midway? It'd be nice if someone can let me know. Thanks!
Edit: I think I just figured it out. The function is not surjective at all in the range $[-1,1]$. Correct me if I'm wrong, thanks!
Edit 2.0: Sorry, it should be not injective in the range $[-1,1]$, right?
Comment: The function $r(x)$ is clearly surjective.  $r(1)=1$ and $r(-1)=-1$.  Since $r$ is a quotient of continuous functions and the denominator of the quotient is non-zero, $r$ is continuous.  Thus, the Intermediate Value Theorem guarantees that $r$ takes on every value in $[-1, 1]$.
Comment: If the function is bijective, it is inheritable.  That doesn't mean that the inverse has a nice representation.
Comment: What means that you solved for the inversen? What did you actually solve?
Comment: Hört do you know that the function is injective? What is the domain of the function?
Comment: " Sorry, it should be not injective in the range [−1,1], right?" does not help a reader to understand the problem, so you should remove it . You can post such statement as comments. But you still have not mentioned what the domain is and why you think it is injective. You should edit your post to clarify the question.
Answer: $y = \frac {2x}{1+x^2}$
If you can isolate $x$ you have your inverse.
$y(1+x^2) = 2x\\
yx^2 - 2x + y = 0$
Using the quadratic formula
$x = \frac {1 \pm \sqrt {1 - y^2}}{y}$
and
$x = f^{-1}(y) = \begin{cases} \frac {1 - \sqrt {1 - y^2}}{y}&y\ne0\\0&y=0\end{cases}$
maps from $[-1,1] \to [-1,1]$
Comment: Why not $x=\frac{1+\sqrt{1-y^2}}{y}$?
Comment: A good question. Hint: Try it with $y=\frac{1}{2}$.
Comment: It doesn't take values back to the correct domain.  It would be the inverse of the function over the domain $(-\infty, -1]\cup [1,\infty)$
Answer: The easiest way to check is to plot the function. If it has a turning point within the allowed domain then it will not have an inverse, since the inverse would need to be many to one. i.e. not a function.

From the plot, it is clear that there are two values for $y=\frac{1}{2}$. Solving for $x$, we see that these are $x=2-\sqrt{3}$ and $x=2+\sqrt{3}$
\begin{align}
\frac{2x}{1+x^2}&=\frac{1}{2}\\
\frac{x}{1+x^2}&=\frac{1}{4}\\
x&=\frac{1}{4}+\frac{1}{4}x^2\\
0&=x^2-4x+1\\
\therefore~x&=\frac{4\pm\sqrt{16-4}}{2}\\
&=\frac{4\pm2\sqrt{3}}{2}\\
&=2\pm\sqrt{3}
\end{align}
Since the function has two $y$ values for at least one $x$, the function is not bijective and does not have an inverse.
Note: the turning points of the function are at $x=\pm1$, if the domain of the function is restricted to this interval, then it will have an inverse. The same is true if $x\in(-\infty,-1]$ and $x\in[1,\infty)$.
Comment: Personally I am quite confused right now as well. I noticed that the function should not be injective and thus not bijective.
Comment: I think writing to use a Plot to prove something is a reason for a downvote.
Comment: I feel like deleting this under peer pressure because of the downvote, and because it disagrees with the other 2 answers: But I do not see my mistake? Could someone please explain to me why this function has an inverse if that inverse is not one to one?
Comment: I have edited it now. Thank you for the advice @miracle173.
Comment: I think some users assume that the domain of the function is [-1,2] and not R.
Comment: @miracle173 If the domain is [-1,2] it still has no inverse, but I think you just made a typo and meant [-1,1]. Either way, there is no mention of a limited domain in the question, only identification of its range.
Comment: Yes, This is a typo. There is Not mentioned a Domain at all.  I think befasse the OP Worte that the function is injective some user assumes ist hat the Domain is [-1,1]
Comment: @Jess does this answer help you?
Answer: You have miscalculated the inverse.  Using the quadratic formula to solve for $x$ in the equation $y(1+x^2)=2x$ yields:
$$x=\frac{1 \pm \sqrt{1-y^2}}{y}.$$
One of those roots is extraneous.  The correct answer is (the continuous extension at $x=0$ of) $r^{-1}(x)= \frac{1 - \sqrt{1-y^2}}{y}.$


Solving IVP $y'=t|y|^\alpha, \ y(0)=1$

Question: Intro: This is a follow up to my post Application of Picard-Lindelöf to determine uniqueness of a solution to an IVP, where I am trying to verify that the below IVP has a unique solution in some interval that includes $0$. This is a nightmare and doesn't work out for me. So I try to go the opposite direction and see whether or not I can come up with something.
I hope it's okay to make this kind of a follow up post, if not please feel free to close it. I also hope someone finds the time to quickly look through this post and tell me whether or not my reasoning is correct.

Problem: Solve the following IVP $$ \begin{cases} y' &= t|y|^\alpha \\ y(0)&=1 \end{cases} $$ where $ \alpha \neq 1$

My approach: This is the first time I am dealing with an absolute value function, so I guess it is reasonable to look into the two cases where $y$ is positive and $y$ is (strictly) negative.
I first want to show that I can divide through the expression $y^\alpha$.
Let $y=0$ then $y'=0 \implies y=c$ but $y(0)=1$ and therefore $c=1 \implies y=1$ which is a contradiction, thus $y \neq 0$. Then I start solving the differential equation. $$ \frac{dy}{dt}=ty^\alpha \iff \frac{dy}{y^\alpha}=tdt \implies \frac{y^{1- \alpha}}{1-\alpha}=\frac{t^2}{2}+C \\ \implies y = \left( \frac{(1-\alpha)t^2}{2}+K \right)^\frac{1}{1-\alpha} $$
Applying initial conditions would lead to $K=1$. Is that correct? Now the same for $y$ negative of course which I will save for now, just substituting $|y|=-y$ into the original IVP.
How could these results resemble uniqueness?
Update: A sudden idea striking me, it seems very tedious but do I need to do a check analysis for $\alpha$? Meaning do the above calculations for $\alpha < 0$, likewise $\alpha > 1$ and $\alpha \in ]0,1[$ ?
Answer: We have that $t\,|y|^\alpha>0$ if $t>0$ and $t\,|y|^\alpha<0$ if $t<0$. This implies that the solution is decreasing to the left of $t=0$ and increasing to the right of $t=0$. In particular $y(t)\ge1$ for all $t$ for which the solution is defined. The function $t\,|y|^\alpha$ is continuous and locally Lipschitz (as a function of $y$) on $D=(-\infty,\infty)\times[1/2,\infty)$. Since the solution never leaves $D$, the solution is unique, and your formula is valid for all $\alpha\ne1$. Observe that if $\alpha>1$, then the solution is defined only for $|t|<\sqrt{2/(\alpha-1)}$.

Solving IVP $y'=t|y|^\alpha, \ y(0)=1$


Generator of a Quotient Group

Question: Along the same vein of another question I've posted is another question that merges group theory with number theory. I havn't taken a formal course on group theory, and is likely why I'm stumped at these questions posed from elementary number theory. The question goes as
Let $p$ be an odd prime and $g$ a generator of the group $(\mathbb{Z}/p \mathbb{Z})^*$. I need to show that either $g$ or $g+p$ is a generator of  $(\mathbb{Z}/p^2 \mathbb{Z})^*$
I'm not sure where to begin. Just need a push in the right direction.
Thanks!
Comment: Show that if $g^{p-1} \equiv 1 \bmod p^2$ then $(g+p)^{p-1} \not\equiv 1 \bmod p^2$.
Comment: Hint: reducing mod $p$ you would have to be a generator too.
Comment: Note that an element of $(\mathbb Z/p^2\mathbb Z)^*$ has order $p(p-1)$ (that is, it is a generator) if it has order $>p$. Note further that is order $\pmod {p^2}$ cannot be smaller than its order $\pmod p$.
Answer: If $g$ is not primitive mod $p^2$, the fact that $\mathrm{ord}(g)$ divides $p(p-1)$ and is a multiple of $p-1$ implies that $\mathrm{ord}(g)=p-1$ exactly.  The same holds for $g+p$.
So if neither $g$ nor $g+p$ is primitive mod $p^2$, we must have
$g^{p-1} \equiv 1 \mod p^2$ and $(g+p)^{p-1} \equiv 1 \mod p^2$.  (In particular, $g^{p-1} \equiv (g+p)^{p-1} \mod p^2$.) Yet
$$(g+p)^{p-1} \equiv g^{p-1} + \binom{p-1}{1}g^{p-2}p \equiv g^{p-1}-pg^{p-2}\mod p^2,$$
and if this is congruent to $g^{p-1}$ mod $p^2$ it follows that $pg^{p-2} \equiv 0 \mod p^2$.  This forces $g \equiv 0 \mod p$ as $\mathbb{Z}/p\mathbb{Z}$ is an integral domain.  This is a contradiction, and our result follows.
Comment: sorry, I'm just re-reading this a couple days later and realized I don't quite understand the line "If g is not primitive mod p2, the fact that ord(g) divides p(p−1) _*and is a multiple of p−1*_ implies that ord(g)=p−1 exactly. We know since  = (Z/pZ)* that |g| in (Z/pZ)* = (p-1). Is this what implies |g| in (Z/p^2 Z)* is a multiple of (p-1)?
Comment: or is it that since |(Z/p^2 Z)*| = p(p-1) that implies there exists a generator of order p(p-1) and hence every element of (Z/p^2 Z)* has order p(p-1) as well.
Comment: ..but am I able to assume right away that (Z/p^2 Z)* is cyclic?
Comment: Let $k$ be the order of $g$ mod $p^2$.  Then $g^k \equiv 1 \mod p^2$, so in particular $g^k \equiv 1 \mod p$.  But this implies that $k$ is a multiple of the order of $g$ in $\mathbb{Z}/p\mathbb{Z}$, which we know is $p-1$ (as $g$ is a generator mod $p$).  In other words, $p-1$ divides $k$.
Comment: More generally, let $\phi :G \to H$ be a group homomorphism.  If $g^k =e_G$, then $\phi(g)^k = \phi(e_G)=e_H$, so $\mathrm{ord}(\phi(g))$ divides $\mathrm{ord}(g)$ (if both are finite).  In our case, our map is projection $\pi: \mathbb{Z}/p^2 \mathbb{Z} \to \mathbb{Z}/p\mathbb{Z}$.

Generator of a Quotient Group


Binding MenuItem's IsChecked to TabItem's IsSelected with dynamic tabs

Question: I have a list of tab items that have views dynamically added to them.  Every time a user adds a view, a new tab item is created.  I'm now trying to bind a menu to a tabcontrol's items so that a user can select from a menu which view is currently the active view.
My menu is bound as such:
<Menu Background="Transparent">
    <MenuItem Style="{StaticResource TabMenuButtonStyle}" ItemsSource="{Binding RelativeSource={RelativeSource FindAncestor, AncestorType={x:Type TabControl}}, Path=Items}" ItemContainerStyle="{StaticResource TabMenuItem}"></MenuItem>
</Menu>

This works fine and has the desired effect (each menu item is a listing of all the open tabs).
I have the following style that binds menu items to the IsSelected property of the tab items:
<Setter Property="IsChecked" Value="{Binding Path=IsSelected, Mode=TwoWay}" />

My problem is, this binding doesn't work.  The binding error message is stating that it can't find the IsSelected property on the view object.  I don't want it to use the specfic view, rather, I want it to look at the tab item that the view is currently bound to.
I've tried the following, but still get a binding error:
<Setter Property="IsChecked" Value="{Binding Path=IsSelected, Mode=TwoWay, RelativeSource={RelativeSource AncestorType=TabItem}}}" />

Which states that it can't find an ancestor of type TabItem for each menu item (which makes sense as the menu item's ancestors are not what it is bound to.)
Is there any way I can get access to the parent of the item that is coming in as a binding so I can bind to its properties?
Update:
Per Yadyn's advice, I decided to create a value converter and return tab items.
public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture) {
        ItemCollection ic = (ItemCollection)value;
        List<TabItem> tabItems = new List<TabItem>();
        foreach (var obj in ic) {
            tabItems.Add((TabItem)obj);
        }
        return tabItems;
    }

This makes binding IsSelected to IsChecked work for static items (TabControls that have their tab items already created), but for the dynamically added views, the Convert method never gets called.  It's like the TabControl is not sending out an update to binders of its items that something has changed.  Here is how the MenuItem is wired up now:
<MenuItem Style="{StaticResource TabMenuButtonStyle}" ItemsSource="{Binding RelativeSource={RelativeSource FindAncestor, AncestorType={x:Type TabControl}}, Path=Items, Mode=OneWay, NotifyOnSourceUpdated=True,  Converter={StaticResource TabControlItemConverter}}" ItemContainerStyle="{StaticResource TabMenuItem}"></MenuItem>

Comment: Is the Menu a child of the TabControl or is it a Sibling? I thought the only children of a tabcontrol that are allowed are TabItems
Comment: More like a sibling.  I define the menu inside a ControlTemplate for the TabControl, so it can call up to the TabControl's items collection.
Answer: TabControl.Items will get you back the views, since that is what you've bound to your TabControl to have dynamic tab views.
Unfortunately, there isn't a property you can bind to on the TabControl directly that will get you a collection of the TabItems. These are actually the ItemContainers for each item in the Items bound collection.
What you might do is create a converter or something. You can try using myTabControl.ItemContainerGenerator.ContainerFromItem and pass in the view object to get back the actual TabItem that wraps it. Then your IsSelected binding will work.
You might consider binding directly to the TabControl itself instead of the Items property. Then the converter can easily do the above call to ContainerFromItem. You'll then have to return a List<TabItems> from the converter by enumerating the Items property yourself (calling ContainerFromItem for each).
Anyway, hopefully this gets you on the right track!
Comment: Got me started on the right track, but didn't quite fix the problem for dynamic views.  Still, got me going.
Answer: Here is something simpler. Define a toplevel viewmodel that holds a collection of viewmodels representing the tabs and menuitems like so
//Not showing here the details of implementing INPC
public class MyCustomCompositeViewModel:INotifyPropertyChanged
{
  public ObservableCollection<CompositeViewItem>CompositeItems{get;set;}
  public CompositeViewItem SelectedItem{get;set;}
}

On the view, bind the tabitems to the CompositeItems collection and bind the selected tab item to the selectedItem. You can bind the MenuItems similarly
The compositeviewitem should provide properties like the name of the item (for display on the tab and menu), and perhaps the additional data the View needs for rendering. Hope this makes sense.


How to assign int values to strings such that strings can be used with arithmetic operations

Question: I would like to replace numeric column names in a DataFrame with their corresponding word names but still be able to sort the column names in order such that 'two' comes before 'eight'.
When learning Python, I came across a concept whereby we could say 'foo' means 3 and 'bar' means 8 such that later on in the program, 'foo' * 'bar' will be interpreted as 3*8 .
The solutions that I have come across so far (e.g this and this) involved explicitly converting the strings to integers before carrying out operations but I would like to assign numeric values to those strings such that python inherently knows what they represent however, I am no longer able to remember the name of the concept so my google search is not going smoothly.
How can I do this?
Comment: I'm voting to close this question because you need to find a tutorial, not do google searches.
Comment: You might be referring to assigning variables. For example, `foo=3` and `bar=8`, then you can do `foo*bar`. no strings involved.
Answer: You can use a dict:
dictionary = {
   "foo": 1,
   "bar": 2
}
print(dictionary["foo"] * dictionary["bar"])

Or override the __mul__ magic method:
class Multi(object):
    def __init__(self, value):
        self.value = value

    def __mul__(self, other):
        return self.value * other.value

foo = Multi(3)
bar = Multi(8)
foo_bar = foo * bar
print(foo_bar)

Comment: The second example could drop the `Multi` wrapping and remove the `.value` extraction at the end and it would work just fine, no real benefit to the wrapping. It might even be what the OP is remembering, binding integers to names and using the names to do the math.


Specifying the random part of a mixed-model in R

Question: Suppose ses is a level-1 predictor of students math score, and sector is a level-2 predictor denoting the type of schools (public vs. private).
Given above, are the following models legitimate (syntax-wise)?
(Note: I don't think I can have sector randomly vary at the school level because sector itself is a school-level predictor, am I right?)
library(lme4)

hsb <- read.csv('https://raw.githubusercontent.com/rnorouzian/e/master/hsb.csv')

m1 <- lmer(math ~ ses+sector + (ses:sector | sch.id), data = hsb)
m2 <- lmer(math ~ ses+sector + (ses*sector | sch.id), data = hsb)

Answer: The 2nd model may not be appropriate because it specifies random slopes for sector which is a level 2 variable, but if you have reason to think that it should vary by school, then it could be OK.
The first model may be appropriate if you have reason to believe the cross level interaction should vary by school, AND it is supported by the data. The problem with this model is that it corresponds somewhat to a model with a (fixed) interaction term but omitting the main effects, and that rarely make sense.

Edit:
I just want to expand on my remark above about fitting random slopes for a variable that does not vary within the grouping factor. Statistically speaking, we might have a dataset where such a model converges without warning. What I am trying to say is that I'm not sure whether I can make sense of such a model. I mean, maybe there are some edge cases, or pathological examples where it does make sense, but I would like to think that in real world situations it would not make sense to specify a model with random slopes for a variable that is constant within groups. One way to help think about this is to plot the data with the outcome on the $y$ axis, the variable in question on the $x$ axis and then to plot a seperate line for each group. This will be impossible since each group's data points will occupy the same value for the $x$ variable and the slope will be undefined.
I should probably admit at this point, to utilising way too much sarcasm in some of my answers on this topic. My justification for doing so is to encourage analysts to think about what their models mean.
Comment: For my edification, I want to see this plot. What would be the variable on the x-axis in the above example given that you noted: *"One way to help think about this is to plot the data with the outcome on the y axis, **the variable in question on the x axis** and then to plot a separate line for each group. This will be impossible since each group's data points will occupy the same value for the x variable and the slope will be undefined."*
Comment: Thanks Rob, but cross-level interaction already includes schools, no? So can you a bit clarify? Please remember we used these models [HERE](https://stats.stackexchange.com/questions/489059/obtaining-correlation-between-random-effects-separately-for-2-groups), but now I have serious doubts about the legitimacy of these models?
Comment: No, I mean the cross level interaction `ses:sector`. The legitimacy of the models depends on 1) whether there  is theoretical (from domain knowledge) justification AND 2) whether they are supported by the data.
Comment: Rob, I may be misunderstanding this. But a cross-level interaction (`ses:sector`) can only be found when we consider the relationship between `math ~ ses` as being random (varying across schools) and then consider how this relation differs between `sector==0` and `sector==1` (as depicted in [**this visual**](https://stats.stackexchange.com/q/490302/140365)), the answer becomes a cross-level interaction. Now, I have difficulty understanding how such a cross-level interaction can AGAIN  `vary by school` and hence the use of `ses:sector`? (*My question is about understanding the syntax only*)
Comment: I agree with you completely. I think you have missed my sarcasm again :)  I will update my answer.
Comment: @rnorouzian ahh good question !! That's rather outside the focus of this question/answer. Please make a new post about how to visualise the folly of fitting random slopes for variables that don't vary within groups, and I will answer it with code and graphics :)
Comment: [HERE](https://stats.stackexchange.com/questions/490919/how-to-visualize-the-folly-of-fitting-random-slopes-for-variables-that-dont-var) is the question.
Comment: Rob, it seems you got busy, in the meantime, you mean this: `hsb10 <- subset(hsb, sch.id %in% unique(sch.id)[1:10]);  ggplot(hsb10) + aes(x=size, y = math) + geom_path()+   facet_wrap(~sch.id)`


How to add custom php field views that returns my custom functions value?

Question: I'm designing a form that creates a user on sign in. After that I'm displaying the data in a view for an admin to approve. I need to add custom PHP code that calls a function that performs approval of users. How can I do that?
In D7, we can add Global:views PHP field to custom php code.
Likewise I need that in D8 also.
Comment: Any suggestions?
Answer: yes in d7 we had php but in d8 (for good reason) this is not the case. You can however create a controller to do the approval functionality,
then in the view create a button or link that passes the user id to it
such as in view make sure you have the user id field then
make a new filed with custom text
Approve user

then in a custom module create a controller  see:
1) https://www.drupal.org/docs/8/creating-custom-modules/adding-a-basic-controller
2) https://www.drupal.org/docs/8/creating-custom-modules/add-a-routing-file
then change the route to use your path and better permission
yourmodule.content:
path: '/your-controller-path-to-approve-user/{user_id}'
....
_permission: 'Administer users'
then in your controller method
example
   public function content($user_id) {
     //do the stuff to approve the user here.
   }

for bonus points you can look in to making it use ajax. eg
https://api.drupal.org/comment/62725#comment-62725
and if this is still not your thing then you will need to look in to
creating custom Twig extensions but far better to go the controller route.
Comment: Thanks Taggart. It worked perfectly!!


Neovim how to exit insert mode without any delay

Question: I've just started a new neovim configuration based on kickstart.nvim.
When I'm working I often want to quickly switch out of insert mode to do something in normal mode in one fluid motion.  However, when I press the Escape key there is about a half-second delay where I'm still in insert mode.
It kind of feels like neovim is waiting to see if I have other keystrokes to chain after that initial Escape.  Is there a way to remove this delay and have Escape instantly register, or some other way to instantly switch from Insert to Normal mode?
Comment: Check key bindings with `:imap ?`. Also, see if the delay persists with a clean environment (`nvim --clean`)
Answer: The time span of switching out depends on a variable named ttimeoutlen and the Wait time for a mapped sequence to complete depends on timeoutlen. Both are global variables, To decrease the time of switching out from insert mode you can add these lines in your nvim config file,
lua
vim.opt.ttimeoutlen = 50 --in milliseconds

vim
:set ttimeoutlen=50 " in milliseconds

Consider seeing :h ttimeoutlen & :h timeoutlen
Additionally, if you're using tmux then you can add this line in your .tmux.conf
set -g escape-time 0