Interpretations of negative confidence interval

Question: Let's say I measured the weights of 50 chickens from my family farm, which keeps 1000 chickens. The sample mean is 5 kg, SEM is ± 3 kg, and the 95% confidence interval is 5 ± 3 * 1.96 = -0.88 kg to 10.88 kg. How should I interpret the results of SEM and CI. Obviously the weight of a chicken should not be negative.

It seems to me SEM has little use except to calculate CI? What quantitative information can we derive from SEM? We can say the true mean weight of the 1000 chickens is likely (very qualitative) to fall between 2 kg to 8 kg (sample mean ± SEM), but do we know the probability?
How to interpret the negative lower bound of CI?
How much probability that the true mean weight will fall in the range between 0 kg - 10.88 kg?
Comment: That seems implausibly high for SEM....  Some monster chickens you have there.
Answer: what you did - you created confidence intervals under assumption that chicken weights are drawn from normal disrtibution (with value range $(-\infty, \infty)$) - in fact these can be drawn from other disrtibution with $\mathbb{R_+}$ support e.g. erlang or chi distribution, but when sample size is $> 50$ we can assume that mean has normal disrtibution - so this value $-0.88$ is effect of that assumption, so you can interpret it as 0... but to do it in strict mathematical way you should find real distribution for chicken weights, then construct propper confidence intervals (which will be different than for normal distribution) and then you will have more accurate estimates and you will drawn= more meaningfull conclusions,
but remember that conclusions you will draw will be conclusions about that sample of 1000 observations you already have!
Comment: (+1) to elaborate on this, your 95% CI tells you that in repeated samplings of your chickens, about 95% of the time will the sample mean fall between -0.88 and 10.88 kg. However, you also know that it will NEVER be less than 0, because the weights are always positive. Thus it also holds that [0,10.88] is a 95% CI. quester is right that you might be able to get better inference with an explicit model, but just using this trick is probably okay for an informal application like this.
Comment: there's no extrapolation here, the definition of a frequentist confidence interval is in terms of repeated samplings from the same process that produced your sample. This is fully mathematically precise.
Comment: Sample size of 50 is pretty arbitrary, and is not really valid with high confidence (e.g., for 99.9% CI), or small alpha (e.g., $\alpha$ = 0.001).
Comment: @SheridanGrant one thing this CI is about history observations... it's very important to think about statistics as a way to describe history not the future..., although extrapolation is only at your own risk since environment of future observations can change
Answer: I would just (first of all) work on logarithmic scale and back-transform the confidence limits obtained on that scale. That way you're assured of positive limits.
Going full Bayes on this is an answer of wide appeal, but as you're asking this question I am not clear that "learn a whole new approach to statistics" is likely to be practical immediately for you.
All confidence limits are at best smart guesses. But it's clear that a negative lower limit is biologically absurd, so you owe it to science to avoid that if possible. I don't go with those who say "just round up to zero". The technique is inappropriate if it produces absurd results.
More generally, a scale on which the data are symmetrically distributed will produce more sensible results than those you cite. A square root or a cube root scale might work better than a logarithmic scale in some cases.
Some of this advice depends on taking your example fairly literally. What's axiomatic is that using logarithms first is guaranteed to yield positive upper and lower limits.
(I regard this answer as consistent with advice to consider a generalized linear model with appropriate family and non-identity link.)
PS Why not bootstrap a CI?
Comment: Transform all the data. Get confidence intervals on that scale. Transform back. Do not follow your recipe, which is not correct. If you are using decent software, it's one line. You don't have to calculate SE separately.
Comment: Thanks @NickCox "you are dismissing a vast amount of good practice" This is unclear to me. There are *plenty* of common practices which are rubbish. Why is inference on back transformation "good practice?" It is not at all clear that transformations of data (as opposed to on stats) get you away from the problem of inference on transformed ≠ inference on untransformed.
Comment: The principle of estimate on a link scale and report on the original scale is central to generalized linear models for one. More specifically, I've often seen this procedure re-invented for geometric means. That's the principle of the geometric mean: it's exp(ave(log()).
Comment: I know you can go through hoops like Oehlert's Delta method to obtain approximately legit variance estimates on untransformed scales for stats on transformed data... but "backtransformation" seems like an inaccurate description of that process. I wonder how to make an effective conceptual boundary on the kind of naive (mis)use of back transformation for inference which I am charging, and the kind of methods you are pointing to?
Comment: @Alexis I am not grasping your point. My point is that I think I am proposing something utterly standard. I just wish the OP would post some data so that we could see how well it works with their real data, but otherwise the generalized linear model literature from Nelder and Wedderburn to Dunn and Smyth is what I am alluding to.
Comment: Sorry to belabor, Nick, I am wondering why the problems with CIs and hypothesis tests I draw out [here](https://stats.stackexchange.com/questions/361150/using-decibels-in-statistics/361153#361153) may not apply?
Comment: @Alexis I suggest that you post a different answer if you have one.
Comment: Hi, thank you for your reply, I am so happy to see an answer not suggesting Bayes. Can you be more specific about the log transformation? What data should be transformed? like exp ( ln( 5) ± ln(3) * 1.96 ))? is there any literature supporting this logarithms-exponent transformation?
Comment: "one line" could be an exaggeration, but given that you have data in a file, taking logarithms, applying a confidence interval calculation and back transforming the limits are the steps. But note what you're doing is getting a CI for the geometric mean.
Comment: In general inference (e.g., CIs) on transformed data (i.e. $f(x)$) ≠ inference on untransformed data (i.e. $x$) because $\sigma^{2}_{f(x)} \ne f(\sigma^{2}_{x})$ in general (and same is therefore true for SEM), so you can't simply "back-trasform" confidence limits to get valid estimates on untransformed data. Bootstrap is a good approach.
Comment: @Alexis Indeed; the procedures are not equal. My leading suggestion -- which is tentative given the question so far -- boils down to an assertion that a CI for the geometric mean may make more sense for a variable necessarily positive and evidently skewed. If you're dismissing estimating on a transformed scale followed by back-transformation, you are dismissing a vast amount of good practice.  Note: I am suggesting transforming all the data, not the mean or SE, as explained in my answer. I know that e.g. the mean or SE of logarithms is not in general the logarithm of the mean or the SE.
Answer:
It seems to me SEM has little use except to calculate CI? What quantitative information can we derive from SEM? We can say the true mean weight of the 1000 chickens is likely (very qualitative) to fall between 2 kg to 8 kg (sample mean ± SEM), but do we know the probability?

Let us begin with an observation.  The SEM is not a descriptive statistic.  It is derived from the data.  It informs you about the sampling error of the statistic but not the uncertainty in the population.  It is an artifact of the measurement process.
Had you chosen a different measurement, such as the median, you would have had different standard errors.  Likewise, had your model been different, you would have had different standard errors.
There is an infinite number of possible confidence interval functions.  You are using the standard one from a textbook, but it is not the only one.  It is a model that has desirable properties, so it is taught, but there could be a different interval if you chose to formally model losses you would obtain from getting a bad sample.
The SEM is providing sample-specific information.  For the purposes of your question, its only use is as an interim step in a calculation.
Confidence intervals tell you the area you have confidence in for the location of the mean (or some other statistic).  Confidence intervals tell you nothing about the distribution of the sizes of the chickens themselves.
The interval you may want is the tolerance interval.  If you wanted to know the range where 95% of your population of chickens is likely to fall, then you want the 95% tolerance interval and not the 95% confidence interval.

How to interpret the negative lower bound of CI?

The bounds of a confidence interval have no interpretation.  They are random numbers.  A function that generates an interval is an $\alpha$ percent confidence interval if, upon infinite repetition, the interval would cover the true value of the parameter at least $\alpha$ percent of the time.
If you create an $\alpha$ percent confidence interval and it is $[a,b]$ then the interpretation is that if you behave as if the true value were inside that range then you would be made a fool of less than $\alpha$ percent of the time once repetitions became very large.
A negative bound is fine.  Let's imagine that we are Mother Nature, and you know the true population mean is at 4 kg.  You should be delighted then because the interval $[-.88,10.88]$ contains the actual value.  The lower bound is indeed non-sense, but Frequentist methods allow non-sense answers as long as it covers the true value a certain percentage of the time.
Also, note that narrow intervals are not better than wider ones.  Narrow ones are not more accurate than wide ones.  They are equally precise in that they cover the true value at least a fixed percentage of the time on large repetition.
To see why, imagine that you divided the population of chickens in half randomly and weighed them.  One-half of the chickens had a narrower interval than the other half.  What about the randomization process made one group more accurate?  Nothing.

How much probability that the true mean weight will fall in the range between 0 kg - 10.88 kg?

That is a model-specific question.  I would be concerned that your data is not normally distributed.  While they are probably normally distributed, given roughly equal ages and diets, the population contains chicks and very old chickens.  I would be surprised to find that they were normally distributed on an uncontrolled basis.
However, if we pretend that the chickens are sufficiently similar to each other to be normally distributed, then we can start to address your question.
First, a confidence interval is not a statement of probability.  If you want a probability, then you will need to use a Bayesian model.  A Bayesian credible interval will tell you the probability that a parameter is inside some range.  Frequentist methods will not do that.
The reason is that there is either a 100% or a 0% chance that the parameter is inside the range, in Frequentist thinking.  In Frequentist thinking, you cannot make a probability statement about a fact.
George Washington either was the first President, or he was not.  That is a factual question and not subject to probability statements.  A Frequentist cannot say, "it is probably raining."  A Bayesian can.  It is either raining, or it is not.  The parameter is either inside the range, or it is not.
What you can say is that you have 95% confidence that the interval covers the parameter. What you cannot say is that there is a 95% chance that the parameter is inside the interval.  That is not true.
What you have confidence in is the procedure and not the data.  Your data is a random collection.  There is supposed to be nothing special about it.  As such, your interval and sample mean are random too.  There is nothing special about them either.  The population parameter, $\mu$, is special.  What makes a sample mean or a confidence interval special in any sense is their relationship to $\mu$.
They summarize the information you have gathered about $\mu$ but are not $\mu$.  The procedure gives you guarantees, if your model is valid, about how often you will make incorrect decisions and take incorrect actions based on the sample that you saw.
Even tolerance intervals require you to state how often you want to be made a fool of.  There is no absolute tolerance interval; there are only intervals given $\alpha$, the data, and the model.
Comment: Thank you so much for your detailed answer, really helped me a ton, I'd give you a hug if I can!
Comment: A lengthy and vigorous statement doesn't save one bad argument
here (among several valid and thoughtful points). You express
unconcern about a negative confidence limit. Without going full Bayes, it
is clear that prior knowledge excludes negative weights as absurd.
Dismissing that implication as irrelevant or unimportant just looks
silly to many non-statisticians. I am one and I wouldn't even try to defend
it to my colleagues or students. At best it looks like a mathematical
joke as when -2 people pops out of a puzzle as an answer that fits the
information.
Comment: (ctd) I suggest that the aim of any interval is to be candid quantitatively
about uncertainty and to do that consistently with the data and with the
precise goal of analysis, but also ideally to do that in a principled
and easy to explain way. Manifestly, that leaves room for different
solutions, including discussion about all those criteria. I regard 95%
(or whatever other fraction) in a frequentist CI, or any other interval,  as uncertainty that I am painting where it belongs in a picture of the data. Putting paint in silly places helps no-one.
Comment: @NickCox actually knowing absurd results are possible is quite important to understanding the methodology.  It is a warning.  You are correct, there is a Bayesian improvement easily possible here.  Nonetheless, there can be reasons not to use a Bayesian method such as a sharp null hypothesis.
Comment: @NickCox you want paint in silly places because it is a warning that something may be amiss.  There are other ways to construct CIs based on other loss functions.  Still, the CI she chose does what she intended it to do.  It covered the parameter, maybe.  A non-parametric interval would have been definitively positive because there were no negative observations.  There are other possibilities as well.
Comment: @NickCox One other thing.  Frequentist methods are ex-ante optimal, not ex-post optimal as Bayesian methods are.  The tradeoff is that you may get insane results $1-\alpha$ percent of the time. I had a conversation with a scientist who was frustrated because the results of his regression were theoretically impossible.  It was correctly specified but the results were nonsense.  Potentially valid slopes were inside the intervals but the best fit slope was not in a valid region.  Boundary conditions are powerful things.
Comment: I have made my main point and I don't see that you have rebutted it, as I infer you have not shifted your position. In case you think otherwise: I am not advocating a Bayesian method because I doubt that it fits the circumstances. If the OP had started with a clear prior and was aiming in a Bayesian direction, then well and good. My own answer gives as main suggestion working on logarithmic scale which avoids completely the nonsense of a negative limit.
Answer: To produce a probability for weights you should really apply Bayesian methods in this case. This is not about frequentism against Bayes, but you have some very strong prior information here: You know, that a chickens weight is not negative and that it is not .5 kg.
Standard frequentist methods are basically open for all results, often presuming normally distributed data and your example is a good example for non-normally distributed data.
Find yourself a credible prior distribution that excludes negative chicken (how about half-normal prior?) and compute a posterior distribution. From that posterior distribution you can conclude real probabilities.


What's your favorite ticketing system?

Question: I'm in the market for a ticketing system and I'm curious what everyone else is using. I'd like to welcome everyone to post their favorite ticketing system and the reason they like it so much.
My criteria in selecting a ticketing system is:

Should be open source
Users should be able to do 100% of their interaction by email. No need to use the web interface at all. I don't even really care if there is a customer web interface.
Should let me handle as much by email as possible. (at least, let me reply to tickets by email)
Should be fairly simple to install with few dependencies.
The web interface shouldn't make me want to gouge my eyes out.

Things I don't really care about:

Time tracking.
Prioritization is not a huge priority. (groan)
Sub-tasks, task depdencies, queues, etc.
Pretty much anything else that doesn't aid getting issues out of my email and into a tracking system.

I've used Trac successfully as a ticketing system in the past (just turned off the wiki, repository, etc) and I wouldn't mind using it or Redmine again if I knew of some email plugins. At a previous company, I used Request Tracker which fulfills nearly all the criteria, but had so many dependencies that nothing else I run needs that I finally just decided it wasn't worth it.
I have OTRS up and running, and it fulfills all the email requirements, was pretty straightforward to setup, but I really dislike the (IT) web interface. Perhaps I'm using it wrong, but the way it handles listing tickets and helping me find what to do is far inferior to RT.
Perhaps I'm just being really nit-picky, but I figure I'm going to have to be using whatever system I choose all day long every day so I might as well really like it. And as long as the users only have to interact with email@example.com, it's transparent to them.
So what are you using/have used that you really really like and why?
Comment: "Perhaps I'm just being really nit-picky" - Yes, you are. The evidence is here: "Request Tracker which fulfills nearly all the criteria, but had so many dependencies that nothing else I run needs that I finally just decided it wasn't worth it." AFAICT, you just install the dependencies and forget them. How is this "not worth it"?
Comment: Every new dependency is a new thing to maintain and keep running, and more complexity to deal with when things go wrong. I'm a firm believer in keeping things as simple as possible, and a ticketing system is supposed to ease my burden, not add to it. If there's nothing better out there, I will probably pick up with RT again. But I want to make sure that there really isn't anything better first.
Answer: Request Tracker all the way.
The dependencies aren't nearly as much of an issue as they used to be, as long as you don't care about having the absolutely latest version.  On RHEL5 systems, you just configure your system to use EPEL and run "yum install rt3".  On Ubuntu, it's something more like "apt-get install request-tracker3.6", but "apt-cache search request-tracker rt3" will give you a list of all the related packages.
Yes, both of those options pull in a whole lot of perl modules, but so?  There's somebody else who's already built them and is worrying about keeping them current.
Comment: I do like RT, and I will keep EPEL in mind if I decide to go back to it.
Comment: @Guss: RT is actually quite extensible, but generally requires some perl programming knowledge. There's a lot you can do with ticket attributes and Scrips, but you can also customize and add more pages with the specific things you need. RTFM and RTIR are both extensions to RT using the same kind of extension mechanisms anybody could use.
Comment: I don't like RT at all - I've worked with a few people that absolutely love this (for example Kannel F/LOSS  project I was involved with in the past used it before moving to redmine), and I think it is way too simplistic and doesn't offer any extensibility that other systems do and its very hard to customize its UI other then selected different colors for products and such.
Answer: We use "RT: Request Tracker" by Best Practical. I'm 99% sure it's open source, but you've already used it, so you should know what it's capable of.
Answer: Opensource:
Redmine ; Definitive. It's easy to use, has a lightweight footprint and it fulfills my needs.
Proprietary:
Jira  ; heavyweight. For realy process management into tickets.
Answer: My favourite is JIRA. It's open source but not free. Works here for more that two years without a glitch. It's main strength are customizable workflows, so you can adjust the tracking system to your own workflow (that people are used to, h+owever bad it is), not vice versa.
Comment: JIRA is by far my favorite ticketing system
Comment: I use JIRA on multiple projects and am frequently frustrated by it - however, I have yet to find one I really like.
Answer: I would have to say OTRS.  First off, its open source and used by many large organizations.  I have implemented it at two companies including where I currently work.  I used it everyday for everything.  It has email to ticket functions and I have it authenticating with AD with ease.  Give it a look or try.  In the past I have used Numara Track-It and it was OK.  But the client was slow and fat.  I think their FootPrints web software would be a much better solution after using Track-It.
Comment: I've been trying OTRs but the one thing I'm stuck on is the day to day workflow. I feel like I'm really missing something. Do you have any resources for a struggling OTRS admin?
Comment: OTRS Documentation is really great.  Also reading through their mailing lists are very helpful, however I never really liked doing that.
Answer: Not trying to be ultra obvious here, but Bugzilla can be configured rather easily to allow bug replies via email and even bug reporting via email. It has a lot of other nice email features such as "whine" (run queries on open bugs and send the output by email), and has tons of available customizations and integrations. Finally installing it is really easy and it mostly wants some perl modules to be there and you can be up and running in no time.
In my company we use it very successfully and integrated it with the developers' IDEs (Eclipse with Mylyn), the subversion SCM (using hooks and WWW::Bugzilla) and even the build system. The QA guys are using Deskzilla which is a brilliant ticket managing desktop application (which also has a Jira version if you go for that).
Comment: Yeah bugzilla is ok, although the UI is too simplistic sometimes. We use the one at cvsdude.com and it's mostly fine with all issues caused by cvsdude itself.
Comment: I agree, though a lot of project have really nice templates that help with Bugzilla quite a lot. Look at the bug submission wizard at bugzilla.gnome.org and bugs.kde.org . The templating system for Bugzilla is extremely powerful, which is one great feature that neither Jira nor RT offer.
Answer: I just started to use FogBugz and like it so far.
Comment: FogBugs is a cool one but expensive :(
Comment: FB is good, but not open source.
Answer: We've started using SpiceWorks here and like it a lot.  The only downside is a bland user portal.
Comment: We use spiceworks as well. It's simple and works well. The user portal (is) rather bland, but it appears abourg doesn't care about it. ;)
Comment: While the option is "free" it isn't open source. FYI: I've been using Spiceworks since 1.0 and love it.
Answer: Hmm, I don't think there are a lot of people that actually like a ticket system, let alone have a favourite one.
If you'd ask which ticket system do you hate most, my answer would be the Remedy Action Request System.
Comment: Ticketing systems are inherently awful because work you don't want to do comes in via them.
Comment: Surely by now somebody should have created a ticketing system that isn't completely awful? I guess it's not a particularly interesting problem to work on.

And I have had the displeasure of working on Remedy as a user. Quite agree with you there, some systems are terrible, but Remedy blows them out of the water in terms of awfulness.
Answer: Request Tracker's fairly solid. We mostly use it for legacy reasons (it's what we have had for the last few years), and it hasn't caused us any grief. It does the job as it should; there's not much more to say.
Answer: We use TrackIT. Been using it for year and years...  so far so good.
Comment: Here is one I've really forgotten about. I will check it out, thanks.
Comment: They also have a product called footprints. Its trackit on crack.
Answer: Assembla is fast and light-weight while providing what you need.
Answer: I've used Kayako before. It runs on Open Source (php/mysql), however it does cost some money. It's not too bad in terms of pricing, but I'm not sure if you were asking for free or just Open Source technology. Everything is done through email, it's easy on the eyes, fairly affordable, easy to install and solid support.
Answer: I've had good experiences with Flyspray.
Comment: Flyspray is supposed to support some email features - at least according to their mailing lists, but I failed to locate mention of such features in the web site or their own tracking system (powered by flyspray, of course ;-) ).
Answer: Simple and great Hosted Solution: Zendesk
Heavy Ticketing with amazing reporting and process management/workflows (also highest barrier of entry): JIRA
Windows based system, integrates with system management, agent deploy: Kaseya

What's your favorite ticketing system?


Hook fires before current_user service can identify current user

Question: I want to make a menu link disappear when a user doesn't have permission to use it.  I tried this code:
function some_module_menu_links_discovered_alter(&$links) {
  $user = \Drupal::currentUser();

  file_put_contents(DRUPAL_ROOT . '/logs/permission.txt', var_export($user->hasPermission('access some module config'), true));
  file_put_contents(DRUPAL_ROOT . '/logs/roles.txt', var_export($user->getRoles(), true));
  file_put_contents(DRUPAL_ROOT . '/logs/id.txt', var_export($user->id(), true));

  if (\Drupal::moduleHandler()->moduleExists('some_module')) {
    if (!$user->hasPermission('access some module config')) {
      $links['some_module.admin']['parent'] = '';
    }
  }
}

And it didn't know that the logged in user existed.  I was logged in as an administrator, and it thought I was anonymous.  I tried the same code in another hook, and it worked.  So, I'm curious:

Why does this hook load before currentUser knows I'm logged in?
And, are there other hooks like this?
Should I try to figure out the current user through another more low-level method?
Or, is there another way to make a menu link disappear when a user doesn't have permission to view it?

EDIT: Providing code to show what I've done.  The menu link is not disappearing when users don't have access to the route it links to.
some_module.settings:
  path: '/admin/config/system/some_path'
  defaults:
    _form: '\Drupal\some_module\Form\SomeModuleForm'
    _title: 'Some title...'
  requirements:
    _permission: 'access some module config'

The users do not have the access some module config permission, yet the menu link is showing up for them.  When they click on it, they get an access denied page.
Answer: Question in the title: Hook fires before current_user service can identify current user
The menu discovery process is not that dynamically, only runs when you clear the cache or make changes that need a rebuild. So the current user while rebuilding the menu has nothing to do with the current user of a request when the menu is displayed.
I want to make a menu link disappear when a user doesn't have permission to use it.
About the question behind this, what do you not like about the default behavior? Drupal doesn't show menu items the user has no permission for. If you want to do more adjustments probably the best place is in preprocess.
Comment: Found two explanations, first the user could have the permission "Link to any page", this would override any permission set in the route, second the menu link has an absolute path instead of a relative internal one. But there are probably more. I would try a standard permission from core to test this, to check if there is something wrong with the module.
Comment: Thanks for the info about the hook.  The menu link is not disappearing for me, though.  I'm not sure why.
Comment: Aww, that was it, 4k4, thanks.  The Link to any page permission was active for the user.  There are so many permissions, I don't even notice some of them.


Constrained global optimization question

Question: Given an example:
Employee A,B,C can work on three tasks 1,2,3.
The value created by each employee on each task are:
A:(9,10,11)
B:(4,5 ,10)
C:(1,3 ,5)
Ideally, A,B,C all work on task 3 will create the highest value.
But there is a constraint that each task can only be worked on by one person.
So the best solution will be A1, B3, C2 with total value of 9 + 10 + 3.
Is there any optimization algorithm can do solve problem like this if I have more people, more tasks and not only one but several people can work on one task together?
Thanks to forecaster, problem solved by using excel solver.
I am trying to replicate this in R now:
https://stackoverflow.com/questions/30225830/how-to-replicate-excel-solver-in-r
Comment: Yes, fairly straight forward, you could use excel spreadsheet solver  to solve an optimization problem like this.
Comment: Thanks forecaster, it worked! I am trying to replicate this in R. Do you have any ideas?
Comment: To be honest, excel solver is much more easy to use due to user interface and it also has evolutionary algorithm to solve integer optimization such as yours, I rarely use R for optimization. You could try optim function and there are few evolutionaly algorithms such as GA/simulated annealing etc,.
Comment: Long time ago I used to be industrial/mechanical engineer, I used to use a software called [lindo](http://www.lindo.com/) optimization system for scheduling/linear programming/integer programming. you could give it a try.
Comment: Thanks forecaster! I found the excel solver is truly convenient as well. However, the other part of my code to generate values are in R, so I'd like to integrate them together.
Answer: Replication in R is answered at:
https://stackoverflow.com/questions/30225830/how-to-replicate-excel-solver-in-r


Get Instagram realtime count likes

Question: Here is how the application is structured:

A cronjob runs every 3 hours making the Instagram Recent Media call -https://api.instagram.com/v1/tags/myhashtag/media/recent?access_token=ACCESS-TOKEN
If any new images have been posted on #myhashtag, then it creates a new article on the instagram content type
Finally a view(gallery) is built based on the images in this new content type. It displays the image's 'like' counter.

It was built this way to add moderation of images, so that when an image is unpublished, it wont show up in the gallery. The publish and unpublish aspect works through a tool page where there is an additional flag to remove from the queue as well.
Question is: Since the gallery view is based on the values stored on an instagram node in contenttype.
Is there a way to update the value for the likes count field without having to make a call to the API everytime any user goes to the gallery page?
 Otherwise the 'like' counts stored on the article become outdated.
Let me know if I can provide more info.
Answer: I don't know anything about the Instagram API, but if you want to keep the like counters up to date you will need to make API calls at some point.
If you expect many viewers then as you say, you probably don't want to make that call every time a user goes to the gallery, I would suggest adding another function to cron that iterates through your currently active Instagram content and refreshes the like counter.
Comment: Thanks for the response.Yes thats the general plan now, I have noticed some sites being able to show count in real-time and was wondering what they are doing in this case. Thus any alternative approaches.
Comment: They're probably not importing the content, choosing to embed it instead.
Answer: There exist a module that integrates instagram with drupal check and see if it could help with your approach  drupagram
Answer: If you want realtime, you're going to have to use JavaScript like node or something to get true real time.
Answer: Have a look at the Menu Badges module to add such notifications to any menu item and/or menu tab of your choice.
Here are some details about it (from its project page):

Provides a method for adding iOS-style badges to menu items. (see screenshot)

Adding Badges to Menus
Once enabled, go to Administration > Structure > Menus, and click "list links" next to the menu containing the target item. Click "edit" next to the item and select the badge to display with the Display Menu Badge select box.
Adding Badges to Tabs
For adding badges to menu tabs, there is a tab under Administration > Structure > Menus called "Tab Menu Badges". Search for the menu router path of the tab you want to alter, then select a badge from the corresponding select box.
Badge Types
The module includes five example badges, and new badges can be created easily with Views. Modules can also supply their own badges with a hook implementation. See the README.txt file for details.

Because of how it integrates with the Views module, you basically reduce the solution for any type of notification to something like "Just create an appropriate view of it". And as per your "... it creates a new article on the instagram content type ..." in your question, it should be straight forward to have such view only count the articles of instagram content type that are "new".
Video tutorials:

Defining Menu Badges with Views in Drupal, from the module maintainer, which shows how to use it for a custom view with a menu tab "unpublished content" within admin/content.
Drupal 7 Menu Badges Module.

Get Instagram realtime count likes


Duplicate a folder (size 150MB - 200MB) of one S3 bucket to another S3 bucket of different region using PHP

Question: I want to copy a folder (size 150MB - 200MB) of one S3 bucket to another S3 bucket of the different region using PHP or in S3 term "duplicate all objects with the prefix of an S3 bucket into objects with a different prefix to another S3 bucket"
I have tried below code but it's not workings
<code>$s3 = new S3Client(['credentials' => $credentials, 'version' => 'latest','region' => $region,'debug' => false ]);
$s3->registerStreamWrapper();
$result = $s3->uploadDirectory("s3://{$source_bucket}/{$key}",$target_bucket);
</code>
and I have also tried to list out all objects (using listObject function) from source bucket then copy it (Using copyObject function ) into destination bucket. But this process is consuming too much time.
Any suggestion
Comment: Have you considered using cross region replication? https://aws.amazon.com/blogs/aws/new-cross-region-replication-for-amazon-s3/
Comment: Thanks for your response @Tim, and I found your solution is perfectly matched to my problem but I doubted, Can I select my client's bucket as a destination bucket. (Client's bucket is in eu-west-1 region and my bucket is in ap-southeast-1 region)
Answer: As per my comment, you should use Cross Region Replication. You can replicate between any region you like. There's more information here.
Update
Cross region replication where source and destination buckets are owned by different accounts, walk-through here.
Comment: While configuration I wasn't able to select destination bucket from the option "Select Bucket" under "Destination". I am wondering how can I select my Client's bucket without configuring it, or in other words,  I am not giving any access key or secret key of client's bucket. How can I access it with just selecting the bucket under "Destination" option (If i able to do)? Please elaborate this a bit more.
Comment: That's a really significant requirement you didn't include in either your question or your follow up comment. I spent 15 seconds on Google and found the answer for you, linked above.


Simplify the following and express in the form $a + bi$

Question: **(a)**$(1+\sqrt{3}i)^{4i}$
I have no problem finding the solution as I simply convert the expression $1+\sqrt{3}i$ into euler/polar form and arrive at the following:
let $z=1+\sqrt{3}i$. Then $$z = 2\cdot e^{\frac{\pi}{3}}$$
Then $$z^{4i} = 2^{4i} \cdot e^{i\cdot i \cdot {\frac{4\pi}{3}}}$$
this simplifies to  $$z^{4i} = e^\frac{-4\pi}{3}\cdot e^{4i\ln(2)}$$
I'm almost certain my solution is correct, however, I have absolutely no idea how one would convert this back to the form $a+bi$.
Is anyone able to provide a method to do so (or perhaps a different solution that would lead us to the solution in the appropriate form).
Comment: The notation here is very unclear and confusing :(
Comment: Any expression following a bracket that looks like it was an attempted (and failed) exponent.. is an exponent :(
- Newbie
Comment: I did my best to convert what you typed into LaTeX format. Does it look okay?
Comment: Yes it does! Thank you.
Answer: You already have your number in polar form $r\,e^{i\theta}$. If $a+ib=r\,e^{i\theta}$, then
$$
a=r\cos\theta,\ \ \ b=r\sin\theta.
$$
So, in your case,
$$
a=e^{-4\pi/3}\,\cos(4\ln2),\ \ \ b=e^{-4\pi/3}\sin(4\ln2).
$$
Answer: Just use Euler's formula: $e^{ix} = \cos(x) + i \sin(x)$. That's how you go from polar to rectangular.


Probability that sum is odd but not divisible by $3$

Question: Out of $20$ consecutive natural numbers two are chosen randomly.Find  Probability that sum is odd but not divisible by $3$.
We have denominator as $\binom{20}{2}$.
Now any number will be of the form $3k$, $3k+1$ or $3k-1$.
Since sum of $3p+1$ and $3q-1$ is divisible by $3$ our chosen two numbers must fall in the following two cases:
Case $1.$ one number is of form $3k$ and another $3p+1$
So select any multiple of $3$ from $20$ numbers and select any number which leaves remainder $1$ from among $20$ which makes sum not divisible by 3.
Case $2.$ one number is of form $3k$ and another $3q-1$
So select any multiple of $3$ from $20$ numbers and select any number which leaves remainder $2$ from among $20$ which makes sum not divisible by 3.
But now how to choose making their sum is odd?
Comment: I think it does not matter, any $20$ consecutive numbers can be linearly mapped to first $20$ naturals
Comment: Is that a random 20, or the *first* 20?
Answer: Because with $20$ numbers you do not have the same number of numbers of the form $3k$, $3k+1$, and $3k+2$, I would recommend considering three separate cases, namely where the series starts with a number of the form $3k$, where it starts with $3k+1$, and where it starts with $3k+2$. For each, figure out how many pairs there would be of the desired property (because of the asymmetry, probably you don't get the same number for each), add them all up, and divide by $3 \cdot {20 \choose 2}$
Just to show how to do this for one case, consider where the first number of the series is of the form $3k$. Now, to add a second number and get an odd sum, we need to either add the second number, or the fourth number , or ... Of those, the 4th, 10th, and 16th will be of the form $3p$, so we rule those out, leaving $7$ numbers that can be added to the first with the desired property. The same $7$ numbers can be added to the 7th, 13th, and 19th number, giving $28$ pairs. Similarly, to the 3rd, 9th, and 15th we can add all but the 6th, 12th, and 18th, so that is another $21$ pairs. Finally, to the 5th, 11th, and 17th we can add all but the 2nd, 8th, 14th, and 20th, giving another $18$ pairs, for a total of $67$ pairs.
Now do the same analysis for the first number being of the form $3k+1$, and then for $3k+2$. Like I said, you may get a slightly different number of pairs for those, but add them all up, and divide by the total number of possible pairs you can get between all these three different sequences, i.e divide by $3 \cdot {20 \choose 2}$
Answer: Note: $\Bbb N = 6\Bbb N+3\{0,1\}+\{0,1,2\}$ and $\Bbb N\times\{0,1\}\times\{0,1,2\}\mapsto \Bbb N$ is a bijection.
Ie: we can uniquely identify every natural number by the form $6a_1+3a_2+a_3$ where $a_1\in\Bbb N,$ $a_2\in\{0,1\}$, and $a_3\in\{0,1,2\}$. Eg: six consecutive natural numbers starting at $6k$ are: $$\{6k, 6k+1,6k+2,6k+3, 6k+3+1, 6k+3+2\}$$
The sum of two numbers of such form, $(6a_1+3a_2+a_3)$ and $(6b_1+3b_2+b_3)$, will be odd but not divisible by three if:

$a_2+b_2=1$ and $a_3+b_3 \in\{2,4\}$, that is $(a_2,b_2)\in\{(0,1),(1,0)\}\text{ and }\\(a_3,b_3)\in\{(0,2),(1,1),(2,0),(2,2)\}$
$a_2+b_2\in\{0,2\}$ and $a_3+b_3 = 1$, that is $(a_2,b_2)\in\{(0,0),(1,1)\}\text{ and }\\(a_3,b_3)\in\{(0,1),(1,0)\}$
Answer: Firstly, you have overlooked two other cases where the criteria holds:
$$
(3n\pm1) + (3m\pm1)= 3(q)\pm2=3k\mp1
$$
where $k=q+1$, $q=n+m$, and $n,m,q,k \in \mathbb N $.
We call this scenario (1). We can then combine the two cases you identified,
$$ 3n +(3m\pm1)=3k\pm1
$$
where $k=n+m$, and $n,m,,k \in \mathbb N $, as scenario (2).
Now, note that the sum in each case above will only be odd if $3k$ is even, which implies that $k$ must be even. We can deduce from this that in (1), $q$ is odd, so one of $n$ or $m$ must be odd and the other even. In (2), we know that $n$ and $m$ are either both odd or both even.
In a sequence of $20$ consecutive integers, ten will be odd and ten will be even. There will also be at most $\lceil\frac{20}{3}\rceil=7$ multiples of $3$. In fact, if the sequence begins on a number $3n$ or $3n-1$ there will be seven multiples of 3, but only six if it begins on a number $3n+1$. We will show that in both cases, the probability of sum $3k\pm1$ being odd is the same.
If there are seven multiples of $3$ in the sequence, either four are odd or four are even. Assume w.l.o.g that four are odd. This means there are six odd non-multiples of $3$ and seven even non-multiples of $3$. From (2) [$n$ and $m$ are either both odd or both even] this gives $4\times6=24$ and $3\times7=21$ sums of the required form.
Now we consider sums of form in (1). Of the six odd non-multiples of 3, three will be of form $3n-1$ and three will be of form $3n+1$. In the even case, there will be either four or three of the form $3n-1$ and correspondingly three or four of the form $3n+1$ (this depends on whether the sequence starts on a multiple of 3). Either way, (1) yields us $3\times4=12$ and $3\times3=9$ sums of the required form. This means in total there are $24+21+12+9=66$ sums.
In the case where the sequence only has six multiples of 3, a similar process delivers $3\times7 + 3\times7 + 4\times3 + 4\times3 =66$ sums, so it does not matter what number the sequence begins on.
All that is left is to find the probability, which is $\frac{66}{{20}\choose{2}}\approx 0.347$.


Pandas :: Values of one column as columns

Question: The data looks like this:
origin_id   type   serialn     event    year    month    day
1              A       101        X1    2017        6     10
1              A       101        X2    2017        6     10
1              B       101        X3    2017        6     10
2              A       151        X1    2016        7     15
2              B       151        X3    2016        7     15
2              C       151        X4    2016        7     15

And I need it to be this way:
origin_id    serialn   X1    X2    X3   X4    year    month    day
        1        101    A     A     B null    2017        6     10
        2        151    A  null     B    C    2016        7     15

So basically what I need is to use the values of the column event as headers and put the value of the column type for each event, when there is no event for a certain origin_id put a null. Some other columns from the dataframe, like serialn and origin_id should be in the resulting one. Also there should be only one row for each origin_id
This question: How to pivot a dataframe touches on some points, altough it's geared towards performing an aggregation at some point.
This is a possible solution.
I get a df with the origin_id as the index, the events as columns and the types as their value.
stat = df.pivot(values='type', index='origin_id', columns='event')

Now I need some information from the original dataframe, so I only keep one event for each origin_id and drop the columns I'm not gonna use
df1 = df.drop_duplicates(subset='origin_id').drop(['type','event'], axis=1)

Merging the both dataframes, df1 using the values of origin_id and stat using the index.
pd.merge(df1, stat, how='inner', left_on = 'origin_id', right_index = True)

Using the first dataframe with the code above I get this result:
origin_id    serialn   X1    X2    X3   X4    year    month    day
        1        101    A     A     B null    2017        6     10
        2        151    A  null     B    C    2016        7     15

Is there another way to do this?
Thanks!
Comment: Thanks for the link @MaxU, I used some bits of it to get to an answer, do you think I can make it in a more direct way?
Comment: I don't know which approach did you chose... I can imagine using `pivot`, `pivot_table` or `set_index` + `unstack`...
Comment: There's and edit in the original question :)
Comment: Can you post a sample data for `df` (`status` column is missing...)?
Comment: Woops, my bad, forgot to change that one, it should be `event`.
Comment: yeah, just realized I got that one wrong again, `event` is the correct one!
Comment: Can you rephrase your question to reflect those new details and post your new desired DF (result of merging)? I'll reopen it then and try to find a solution
Comment: I don't understand why do you want to keep all those duplicates... What about: `df.pivot_table(index=df.columns.drop(['event','type']).tolist(), columns='event', values='type', aggfunc='first').reset_index()`?
Comment: Works like a charm, shorter and more readable. The only thing is that the status becomes the index and I don't really know why. If you want post it as an answer so I can pick it :)
Answer: You can do it this way:
In [85]: df.pivot_table(index=df.columns.drop(['event','type']).tolist(),
                        columns='event',
                        values='type',
                        aggfunc='first') \
            .reset_index()
            .rename_axis(None,1)
Out[85]:
   origin_id  serialn  year  month  day X1    X2 X3    X4
0          1      101  2017      6   10  A     A  B  None
1          2      151  2016      7   15  A  None  B     C


difference between Nested Cross Validation and Hold-one-Out

Question: I understand that for small sample sizes its best not to opt for the traditional hold out validation but rather use the entire dataset and perform a k-fold cross-validation. However in my case i want to find the best hyper-parameters and select the best model, i understand that in this case a nested cross validation may be the better option.
If I understand the method of nested cross validation, i.e. take your entire dataset and split it into 2 folds. You then take each fold and perform a k-fold cross validation to determine best hyper-parametes on one fold. And for the other fold you perform a k-fold cross validation to determine the best model. Is my understanding of cross validation correct
 and if so how is this any different to hold one validation?
Comment: I still didnt get the second part. You are splitting your data into 2 sets to do a k-fold cv on each?
This would not be "nested" CV, only 2 CVs.
In nested CV, there is an outer loop and an inner loop. The inner part is usually to fit a model and the outer is for hyperparameter tuning.

In contrast, the Hold-Out method reserves a certain amount for testing (1/3) and uses the remainder for training (2/3).
Comment: Thanks @Inathan, i understand that but i fail to see how nested cross validation methods works to ensure that the inner loop does not leak data into the outer loop during training  - does that make sense?
Answer: Your fundamentally misunderstood the concept of cross validation.

$k$-fold cross validation: Have 1 loop

Equally divide dataset into $k$ folds.
For $i \in [1;k]$, test models on the $i$-th fold and train on the remaining folds.
The final result is the average results of $k$ testing folds.

nested $k$-fold cross validation: Have 2 loops.

For every $i$ above, we have a $k$-fold cross validation nested inside.

Holdout: literally hold a set of data out for testing.

In your case, when you split the data into 2 folds and perform two different tasks on each fold, you are not doing cross validation. The key thing to remember that whatever you want to do, you have perform it independently for every $i \in [1;k]$.
Thus, in your case, the correct way should be:

In the inner loop, you select best hyper-parameters by subsequently using different hyper-params to train model on the inner training folds and test on the inner testing fold.
Then use the best models selected in the inner loop to test on the outer loop.
The average results of the outer loop is the estimated performance of your model.


registering app / deploying with Google App Engine and Android

Question: I am trying to deploy a very simple app on app engine using Eclipse and the provided Google plugin.
I created the simplest possible android app which starts the RegisterActivity generated by the plugin, where I did plug the ID, Api Key and project number. I then click on the button but I get this error message :
<code>11-25 16:53:50.372: E/com.example.a123.GCMIntentService(25146): Exception received when attempting to register with server at https://blabla-my-app67.appspot.com/_ah/api/
11-25 16:53:50.372: E/com.example.a123.GCMIntentService(25146): com.google.api.client.googleapis.json.GoogleJsonResponseException: 404 Not Found
11-25 16:53:50.372: E/com.example.a123.GCMIntentService(25146): Not Found
</code>
Although, the console tells me that there is one instance up and running and the LOCAL_ANDROID_RUN variable in CloudEndpointUtils.java is set to false.
Indeed, it seems that for instance this URL : http://blabla-my-app67.appspot.com/_ah/api/explorer%20pagereturns me 404 error.
How is that possible and what can I be doing wrong ?
Thank you a lot in advance.
Al
EDIT :
blabla-my-app67.appspot.com/_ah/api/explorer is not a 404 but http://blabla-my-app67.appspot.com/_ah/api is.
EDIT SOLUTION :
You absolutly need to be compiling with java JRE 1.7 !!
Comment: Found solution : You absolutly need to be compiling with java JRE 1.7 !!
Answer: SOLUTION
You absolutly need to be compiling with java JRE 1.7 !! 1.8 does not work..


Get days, hours, minutes, and seconds left

Question: I am using Drupal 8 and trying to fetch how many time is left to start a event. I have future date.
when I do {{content.field_event_start_date_time }} it outputs:
Thu, 05/20/2021 - 12:00 which is my start date of the event

Now, I used following code to calcuate days difference that is not working:
{# endDate and startDate are strings or DateTime objects #}
{% set difference = date({{content.field_event_start_date_time  }}).diff(date(startDate)) %}
{% set leftDays = difference.days %}
{% if leftDays == 1 %}
  1 day
{% else %}
  {{ leftDays }} days
{% endif %}

any idea how can I get days, hours, minutes and seconds left?
Comment: You can use Carbon library of php. Or moment library of js.
Answer: Do not include too much logic into the view layer. It makes the code less readable. Views should mostly receive variables calculated in Drupal's hook system.
I would recommend using hook_preprocess_HOOK(), and calculate the date there.
For example, in your theme file:
function hook_preprocess_YOUR_VIEW_NAME(&$variables) {
  $variables['my_date'] = // ... calculate your date
}


Point-set topology, characterizing sets

Question: I think the question sort of speaks for itself. Please no solutions in the answers - I'm mostly looking to see if my logic makes sense:

Let $E$ be a set in a metric space $(X,d)$. Let $E^{\circ}$ bee the interior of $E$, $\partial E$ be the boundary of $E$, $E_{isol}$ be the set of isolated points in $E$, and $E'$ be the derived set of $E$. Characterize the following sets:

$E\cap\partial E=E_{isol}$ -> Boundary points are ones where each $\delta$-ball has a point in $E$ as well as $E^c$. They need not be in $E$, but this intersection forces them to be in $E$. Meanwhile, isolated points are points in $E$ where there exists a $\delta$-ball in which they are the only point of $E$. They are required to be in $E$, and also require any ball to be in $E^c$, by definition. Seems like a fit to me.
$E^{\circ}\cap E'=E^{\circ}$ -> Interior points are ones where some $\delta$-ball about them is contained in $E$. Limit points are ones where each ball about them contains another point in $E$. It seems, by my thinking, that the interior of $E$ is contained in the derived set; if there is some ball about a point entirely contained in $E$, then surely every ball about said point will contain another point of $E$.
$E'\cap E_{isol}=\emptyset$ -> A clash of definitions here. Isolated points must have a ball about them where they are the only element of $E$, while each ball around a limit point must contain something in $E$.
$E^{\circ}\cap E_{isol}=\emptyset$ -> Again, a clash of definitions. No ball with non-zero radius around an isolated point can be contained in $E$.
No formal proofs or anything needed - just developing intuition and working on internalizing the definitions of these sets/points.
Comment: In general, the intersection of the interior of $A$ and the set of isolated points of $A$ is *not* empty - consider the set of natural numbers with discrete metric. Every subset of this space is open every point in this space is isolated.
Answer: Your second and third answers are correct, for the reasons that you give; the other two are not in general correct. I won't give you the correct answers, but I will give you counterexamples to your two false conjectures.

$E\cap\partial E$: Take $X=\Bbb R$ with the usual metric and $E=[0,1]$; then $\partial E=\{0,1\}$, so $E\cap\partial E=\{0,1\}$, but $E_{isol}=\varnothing$.
$E^\circ\cap E_{isol}$: Let $X=\Bbb Z$ with the usual metric, and let $E$ be any non-empty subset of $X$. Then $E^\circ=E_{isol}=E\ne\varnothing$. (This is essentially tetori's example in the comments.)

Point-set topology, characterizing sets


iOS change tabbar item color is safe?

Question: I am properly using following method to change tabbar icon color,
<code>[tabBarController.tabBar setSelectedImageTintColor:[UIColor redColor]];
</code>
but before using it I read some posts about apple's app rejection due to this issue. I assume that if is an ios5 method must now be accepted. Is it true? Thanks.
Answer: It won't be rejected, but you'll have to set your deployment target to iOS 5 and people running iOS 4 won't be able to download and install your app.
To use this method only on iOS 5, and still allow the app to work on iOS 4 (with blue tabs) do this:
<code>if ([UITabBar instancesRespondToSelector:@selector(setSelectedImageTintColor:)])
{
    [tabBarController.tabBar setSelectedImageTintColor:[UIColor redColor]];
}
</code>
This code is safe to run on iOS4.
Alternatively, see my answer to this question that explains how to fully customise the tab icon colours in a way that works on any iOS version: tabbar item image and selectedImage
Comment: thanks, so is there any way that people that runs under iOS4 could download the app but this method will not be executed and instead show always default blue color? possible?
Comment: awesome solution, tested and working! really useful, thanks again
Answer: I didn't try it myself but I took a look at the UITabBar Class Reference. The property selectedImageTintColor is documented. So this means, you are allowed to use it. Normally Apple only rejects application that use undocumented (not public) APIs. So you are safe to use it.
You can see there too that the property is available in iOS 5 and later.
Answer: You can check this post on how to determine the current iOS version and do the appropriate tab bar item color setting for users running iOS 5 or lower. Hope this helps.
Comment: Using instancesRespondToSelector: (see my answer) to check if the method exists is a better approach than testing the iOS version. That means you don't need to keep track of exactly which iOS version introduced each feature.

iOS change tabbar item color is safe?


Multiple forms in same page from single form builder returning the first form's value in submit

Question: I have written a single form builder and a form submit handler corresponding to that form.
What I have done is that I have rendered the form multiple times using for loop and then concatenated them into a single variable and then displayed it on a single page.
Each form has separate submit buttons.
But the problem is that whenever I press the submit button of any of the forms I am only getting the form that was built first in the form_state['values'] in the submit handler.
For now, I have made it work by taking the form_state['input'] which seem to have the correct set of values based on the form submit clicked.
I need the corresponding form values in the submit handler. How can I achieve this?
Is this some kind of bug or am I doing it wrong?
$form_markup = '';
  foreach ($ids as $key => $value) {
    $req_form = drupal_get_form('_request_form', $value, $key, $node);
    $form_markup .= render($req_form);
  }

My form and form_submit
function _request_form($form, &$form_state, $value, $key, $node) {
    $form['name'] = array(
      '#type' => 'item',
      '
    );
    $form['submit'] = array(
      '#type' => 'submit',
      '#value' => 'Ask',
    );
    return $form;
  }
}

    function _request_form_submit($form, &$form_state) {
      dpm(form_state['values']);
      dpm(form_state['input']);
    }

Any help is much appreciated.
thanks.
Answer: You'll need to implement hook_forms(), so that you can create 'aliases' of your forms.
For example, let's imagine a form named 'message_form', that you want to include multiple times on the page. To do this, you append a unique number to the form name each time when calling the form:
$page = [
  'form_1' => drupal_get_form('message_form-1'),
  'form_2' => drupal_get_form('message_form-2'),
];

return $page;

Next, you implement hook_forms() to watch for form names in the format above:
function hook_forms($form_id, $args) {
  // Act on form IDs that match the pattern message_form-[NUMBER].
  if (preg_match('/^message_form-\d+$/', $form_id)) {
    // The key is the form ID that has been passed.
    $forms[$form_id] = [
      // The callback is the actual form definition to be called.
      'callback' => 'message_form',
    ];
  }
}

Now each form being put on the page will have a custom form ID and therefore the system will know which form the submitted data refers to.
Comment: I tried something similar to this. Whenever the form hook was called I had assigned a unique value to the form_id but still it didnt work.
Comment: This is how you do it. If it didn't work, you did something wrong. Did you implement hook_forms()? Update the original post with your code that is not working.
Comment: I will update it when i try the method that you suggested. thanks


Iptables list doesn't persist across restarts

Question: I am trying to white list CloudFlare's IP addresses on my server by issuing these:
iptables -N whitelist
iptables -A whitelist -s 18.104.22.168/24 -j ACCEPT
iptables -A whitelist -s 188.8.131.52/21 -j ACCEPT
iptables -A whitelist -s 184.108.40.206/20 -j ACCEPT
iptables -A whitelist -s 220.127.116.11/22 -j ACCEPT
iptables -A whitelist -s 22.214.171.124/18 -j ACCEPT
iptables -A whitelist -s 188.8.131.52/18 -j ACCEPT

and when I type: iptables -L I see:
Chain whitelist (0 references)
target     prot opt source               destination
ACCEPT     all  --  network/24           anywhere
ACCEPT     all  --  126.96.36.199/21      anywhere
ACCEPT     all  --  126.96.36.199/20      anywhere
ACCEPT     all  --  126.96.36.199/22      anywhere
ACCEPT     all  --  220.127.116.11/18      anywhere
ACCEPT     all  --  220.127.116.11/18     anywhere

then I restart iptables by doing service iptables restart. However, nothing changed and it didn't white list those IPs :( Am I missing something?
Comment: Are you referencing the `whitelist` chain from anywhere?  What's your `INPUT` chain look like?
Answer: You need to save the configuration before restarting.  On Redhat systems, this goes in /etc/sysconfig/iptables.  The easiest way to do this is:

Issue your commands
run iptables -L to check the config
run service iptables save
run service iptables restart to reload
check the config again with iptables -L


Questions about finite sequences of natural numbers with distinct partial sums

Question: I have a school assignment to do, but I have no idea, where to start. I hope you can help. Here it is:
We have a finite sequence $A = (a_1, a_2,\ldots, a_n)$, length of $A$ is $n$, elements of $A$ are natural numbers.
Let $S(i,j)$ be partial sum of this sequence from $a_i$ to $a_j$, where $1\leq i\leq j\leq n$.
Formally written as $S(i,j) = a_i+a_{i+1}+\cdots+a_j$.
We can call sequence $A$ "nice", when all partial sums $S(i,j)$ are different from each other.
Formally written - For every $1\leq i\leq j\leq n$ and $1\leq k\leq l\leq n$ it holds that "$S(i,j)=S(k,l)$ implies $i=k$ and $j=l$".
E.g. $(1,3,2)$ is "nice" and $(1,4,2,3)$ is not "nice".
I have following tasks:
Prove that for every natural $n$ a "nice" sequence exists.
The main question:
What is the smallest possible value of the greatest element of a "nice" sequence $A$ of length $n$? Or in other words - for every $n$ find the smallest natural number $p$ for which a "nice" sequence $A$ of length $n$, in which no element is larger than $p$, exists.
Hint: search for upper and lower bounds on $p$ in the form of appropriate functions of $n$.
Comment: For part 1, try to build the sequences. Start with a simple sequence, for instance 2 elements, so that it is nice. Then see what number you can append to this sequence so that the result is still a nice sequence. Then continue the procedure, see what you can append. Try to see if there is a systematic rule.
Comment: For the first question, can you find a set of size n such that all subsets have different sums?  That is, we are ignoring the order on A but picking arbitrary subsets.  This gives you an upper bound for p(n).  The order just restricts what subsets you need to consider and may help you reduce p.
Answer: Here is a construction of nice sequences of any length $n$.
Let $a_k = 2^k$, and consider $(a_1, \dots, a_n)$. Now let $1 \leq i \leq j \leq n$, then
$$S(i, j) = 2^i + \dots + 2^j = 2^i(1 + \dots + 2^{j-i}) = 2^{i-1}(2^{j-i+1}-1).$$
Now suppose that $1 \leq k \leq l \leq n$, and $S(i, j) = S(k, l)$, then
$$2^i(2^{j-i+1}-1) = 2^k(2^{l-k+1}-1).$$
As $2^{j-i+1} - 1$ and $2^{l-k+1} - 1$ are both odd, $2^i = 2^k$, and therefore $i = k$.  It then follows that $2^{j-i+1} - 1 = 2^{l-k+1} - 1 = 2^{l-i+1} - 1$ so $j-i+1=l-i+1$, and therefore $j = l$.
Hence $(a_1, \dots, a_n)$ is a nice sequence.


how to keep track of linux package updates across multiple servers / containers (replacing apticron)

Question: I run multiple servers and in each a dozen containers (lxc).
I'm still using apticron to get informations about new package updates but I start to drown in emails from each and every container and usually they report the same update since they're all similar.
What I really need to know is: what package updates are pending on which nodes (preferably in one message).
Basically I like apticron but the number of emails is getting out of hand.
(thought about using icinga2 but it would lack information and also notify for each node individually)
this doesn't answer my question and ocsinventory is to heavy for this job: How to monitor package versions across multiple (Linux) servers
Answer: so I went ahead and built a python script which does the trick
it's my first python so have mercy
the script has to run as root, depends on apt, apt-listchanges being installed and makes only sense if you run lxc, but i guess the lxc-attach could be switched in favor of running the command over ssh.
it lists each package only once and which hosts are affected, also it lists the combined changes in detail.
output:
<code>apt-monitor on ***
2017-04-16 20:28:25.394625 UTC

----- packages -----

linux-image-4.9.0-0.bpo.2-amd64
    version old: 4.9.13-1~bpo8+1
    version new: 4.9.18-1~bpo8+1
    affected hosts:
     - master

tzdata
    version old: 2017a-0+deb8u1
    version new: 2017b-0+deb8u1
    affected hosts:
     - master
     - service-mysql
     - www-stage

----- changes -----
linux-signed (4.4~bpo8+1) jessie-backports; urgency=medium

  * Rebuild for jessie-backports
  * Update to linux version 4.9.18-1~bpo8+1

 -- Ben Hutchings <firstname.lastname@example.com>  Wed, 12 Apr 2017 15:50:11 +0100

linux-signed (4.4) unstable; urgency=medium

  * Update to linux version 4.9.18-1

 -- Ben Hutchings <email@example.com>  Thu, 30 Mar 2017 17:43:56 +0100

tzdata (2017b-0+deb8u1) stable; urgency=medium

  * New upstream version, affecting the following future timestamp:
    - Haiti resumed observance of DST in 2017.

 -- Aurelien Jarno <firstname.lastname@example.com>  Thu, 06 Apr 2017 11:53:44 +0200
</code>
code:
<code>#!/usr/bin/python

import re
import string
import subprocess
import sys
import datetime
import socket

# extract updates from apt output
def collect_upgrades(host, changes, upgrades, is_lxc):
  changes = changes.split('\n')
  pattern = re.compile('^Inst ([\S]+) \[([^\]]+)\] \(([\S]+) [^\[]*\[([^\]]+)\]\)')
  for change in changes:
    if pattern.match(change):
      matches = pattern.search(change)
      upgrade = {'name' : matches.group(1), 'version_old' : matches.group(2), 'version_new' : matches.group(3), 'suffix' : matches.group(4), 'hosts' : [], 'is_lxc' : is_lxc}
      key = upgrade['name']+'_'+upgrade['version_new']
      if not key in upgrades:
        upgrades[key] = upgrade
      upgrades[key]['hosts'] += [host]

# distinct package update lookup
upgrades = {}

# gather changes from host and containers
changes = subprocess.check_output(['apt-get', '--just-print', 'dist-upgrade'])
collect_upgrades('master', changes, upgrades, False)

containers = subprocess.check_output(['lxc-ls', '-1']).strip().split('\n')
for container in containers:
  changes = subprocess.check_output(['lxc-attach', '-n', container, '--', 'apt-get', '--just-print', 'dist-upgrade'])
  collect_upgrades(container, changes, upgrades, True)

# if upgrades is empty we can exit
if not bool(upgrades):
  sys.exit(0)

# collect details apt-listchanges output for each package update
# also print upgrades

# print header

print 'apt-monitor on '+socket.gethostname()
print str(datetime.datetime.utcnow())+' UTC'
print ''
print '----- packages -----'

apt_changes = ''
for key, upgrade in upgrades.iteritems():
  deb_file = '/var/cache/apt/archives/'+upgrade['name']+'_'+upgrade['version_new']+'_'+upgrade['suffix']+'.deb'
  if upgrade['is_lxc']:
    container = upgrade['hosts'][0]
    apt_changes += subprocess.check_output(['lxc-attach', '-n', container, '--', 'apt-listchanges', '-f', 'text', deb_file])
  else:
    apt_changes += subprocess.check_output(['apt-listchanges', '-f', 'text', deb_file])
  print ''
  print upgrade['name']
  print '    version old: '+upgrade['version_old']
  print '    version new: '+upgrade['version_new']
  print '    affected hosts:'
  for host in upgrade['hosts']:
    print '     - '+host

print ''
print '----- changes -----'
print apt_changes
</code>


C# .NET Core Discord Music Bot

Question: so I'm looking to code in some music functionality to a bot that I'm making. I've tried a whole bunch of different search terms but can't seem to come up with anything.
I'm writing the bot in C# .NET Core
I've got the basics down. Connects to a voice channel etc. But I'm not sure how to interface it with YouTube/Spotify so that it could search for url's or song titles.
So for example I'd like to be able to give it a link like this (either youtube or spotify):

Or be able to search Youtube (or both) for a song title:

I'm sure there's some kind of library to download or a NuGet package or API that I can integrate, but I just can't seem to find the right search terms to use to find any tutorials or documentation on the topic.
Any help in this area would be appreciated
Comment: If you still need help see your DM on Discord.
Answer: Well I have been in your shoes and the best solution is to abandon all native ffmpeg and all and just use Sharplink. It uses lavalink to send audio to discord without actually connecting to it.
DiscordSocketClient client = new DiscordSocketClient();
LavalinkManager lavalinkManager = new LavalinkManager(client, new LavalinkManagerConfig
{
    RESTHost = "localhost",
    RESTPort = 2333,
    WebSocketHost = "localhost",
    WebSocketPort = 2333,
    Authorization = "YOUR_SECRET_AUTHORIZATION_KEY",
    TotalShards = 1
});

This is how you would get started.
Once a LavalinkManager is set up it will need to be started. It is recommended you put this in the ready event.
client.Ready += async () =>
{
    await lavalinkManager.StartAsync();
}

Real the docs at https://github.com/Devoxin/SharpLink
Good Luck
**EDIT: **
I made my music bot public so https://github.com/rishav394/Dota-Geek/ here it is. Look out for the music section.
Comment: Ok thanks :)
Much appreciated and will try this out. I've had a couple of other people suggest lavalink with victoria. So I'll definitely use your code as a starting point. I've moved on to some more pressing admin utilities at the moment, but I'll get back to you when I test this
Comment: @JackMcCall Sure :)

C# .NET Core Discord Music Bot


commandButton actionListener isn"t called when an other component is required

Question: I tried
 as shown above, it works correctly.

But, when I tried ti nest this in my global page inside layout, panel, panel-Grid and field-Set, addEquipement() method is not called !
also, thee some fields which have required attribute set to true, I think this is why addEquipement() method isn't called.
Have you an Idea how to fix the problem.
thank you
Comment: Any javascript errors? Server logs which show some errors? Maybe an exception in any of your setters? If there a `h:form` wrapped around? You can omit the parenthesis when using `actionListener` and not passing any parameters.
Answer: I fixed the problem by adding process attribute to
 set to @this.


Breaking gut strings even if the instrument is 'parked'

Question: One of my lever harps got natural gut strings which I am currently not playing (carpal tunnel syndrome, sigh), it's parked in the living room. However, sometimes any gut string will just break at any moment, perhaps once a month usually in the upper 2 octaves (1st and 2nd octave).
The tension is pretty hard but not as hard as a pedal harp. I heard about the breaking point of strings, and that the harp tension is usually around 50%-60% of the breaking point.
Another fact is air humidity by around 40%, pretty constant. Temperature between 19-23 Celsius (66-74 Fahrenheit).
So the question is, why do they break? How can I avoid that? Should I park an instrument by lowering the tension, but what about changes of tension for soundboard and neck?
Comment: Gut strings don't have much of a lifetime in general.
Comment: i must admit i don't have the guts for strings like these. These strings make me sick to my stomach.
Comment: @NeilMeyer  shame! shame!
Answer: Surfing various harp-help fora suggests that gut string life is never very long.
Here's one bit of advice from some string-selling shop,

Gut strings are covered with a protective layer of varnish or a
  lacquer that is slowly worn away by use. Once that protective layer
  has gone, the string will probably not last much longer as it becomes
  more hydroscopic (sensitive to moisture and temperature change). A
  sure sign of this happening is when the fibres of the string starting
  to fray and peel off. Spotting this will mean that you may be able to
  pre-empt a string breaking and change it first

So if your strings had been used for a while, they may have been in "stage one" of death, and then time & humidity took their toll on your harp.


How to transfer data from the program's created field to the standard text, while saving the node?

Question: Using hook_form_alter(), I created 4 form fields. When saving a node, I want to extract data from them and transferred to a standard field.
Using foreach(), I can form a string and then transfer it to the standard field, but how do I get the data from the form input, while saving material?
I use hook_node_presave($node) but it already takes $node as argument, in which there are no custom fields. I do not know how to transfer them here and already work with hook_node_presave().
$form['field_cadastral_num'] = array(
    '#type' => 'fieldset',
    '#title' => 'test',
    '#attributes' => array(
        'class' => array(
            'field-type-text',
            'field-name-property_node_form'
        ),
    ),
  '#weight' => $instance['widget']['weight'],
);
$form['field_cadastral_num']['cell'][] = array(
  '#type' => 'textfield',
  '#default_value' => '',
  '#size' => 3,
  '#maxlength' => 3,
  '#name' => 'kadastr[0]',
  '#value' => ''
);
$form['field_cadastral_num']['cell'][] = array(
  '#type' => 'textfield',
  '#default_value' => '',
  '#size' => 3,
  '#delta' => 3,
  '#maxlength' => 3,
  '#name' => 'kadastr[1]',
  '#value' => '',
  '#prefix' => ':'
);
$form['field_cadastral_num']['cell'][] = array(
  '#type' => 'textfield',
  '#default_value' => '',
  '#size' => 6,
  '#maxlength' => 6,
  '#name' => 'kadastr[2]',
  '#value' => '',
  '#prefix' => ':'
);
$form['field_cadastral_num']['cell'][] = array(
  '#type' => 'textfield',
  '#default_value' => '',
  '#size' => 3,
  '#maxlength' => 3,
  '#name' => 'kadastr[3]',
  '#value' => '',
  '#prefix' => ':'
);

Answer: I would suggest you create the 'cell' fields through the Drupal UI (admin/structure/types/manage/xxxx/fields) so they are registered correctly as part of the content type, then their values will be available in hook_node_presave().


How to do ProxyPass to a tomcat and a static website both?

Question: I have an apache installed on amazon linux there I have tomcat and static website and both should serve through apache.
This is my first conf file (app_name.conf)I have done proxy pass like this :--
<VirtualHost *:80>

ServerName example1.com

ProxyPreserveHost On
ProxyPass           /app_name http://example1.com:8080/app_name/
ProxyPassReverse    /app_name http://example1.com:8080/app_name/

</VirtualHost>

This proxy pass is for tomcat.
I have one static website (/var/www/example2) and confi file (example2.conf) is like this :--
<VirtualHost *:80>

    ServerName www.example2.com
    ServerAlias example2.com
    DocumentRoot /var/www/example2
    ErrorLog /var/www/example2/error.log
    CustomLog /var/www/example2/requests.log combined

</VirtualHost>

Problem :-- Before I was having only one Virtual Host (upper one) and it was working fine but now I added one more Virtual Host.
Now I'm not able to access second Virtual host (example2.com) Its redirecting to first only.
Any Help highly appreciate !!!
Answer: In Apache 2.2 to define several virtualhosts for the same ip:port combo, for example *:80 you need to define this directive once and in server config context:
NameVirtualHost *:80

Apache 2.2 can't distinguish between named virtualhosts if you don't define this directive. Also note this directive is only necessary/valid for 2.2.x, 2.4.x version of Apache does not need it anymore.


Quadratic Variation of a continuous function

Question: I have got the following problem, but no idea where to start, so maybe one of you can help me out. We have got a continuous function $f:[0,1]\to \mathbb{R}$ with $f(0)\neq f(1)$. The task is to construct a sequence of partitions $\Delta_n :=\lbrace 0=t_0,t_1,\dots, t_{k_n}=1 \rbrace $ such
a) the corresponding sequence of mesh sizes tends to zero,
b) the quadratic variation of $f$ along $\Delta_n$ is zero, this means $\lim_{n\to \infty} \sum_{i=1}^{k_n}(f(t_i)-f(t_{i-1}))^2=0$.
I understood, that for $f$ Lipschitz this holds for any partition sufficing a), but since this condition is not given I do not have really an idea how to find the partition.
I am grateful for any hint (or counterexample, if the statement is just wrong and a prerequisite was forgotten in the exercise).
Answer: If $f$ is continuous and of bounded variation, then any sequence of partitions $\Delta_n$ with $\|\Delta_n\| \to 0$ as $n \to \infty$ will suffice.
We have
$$\sum_{j=1}^{k_n}|f(t_j) - f(t_{j-1})|^2 \leqslant \sup_{1 \leqslant j \leqslant k_n}|f(t_j)-f(t_{j-1})|\sum_{j=1}^{k_n}|f(t_j) - f(t_{j-1})| \leqslant \sup_{1 \leqslant j \leqslant k_n}|f(t_j)-f(t_{j-1})|V_0^1(f)$$
Since $f$ is uniformly continuous on the compact interval $[0,1]$, for any $\epsilon >0$ there exists $\delta > 0$ such that for all $x,y \in [0,1]$ with $|x-y| < \delta$ we have $|f(x) - f(y)| < \epsilon/V_0^1(f)$.
If $\|\Delta_n\| \to 0$ then there exists $N$ such that $\|\Delta_n\| < \delta$ for all $n \geqslant N$.
Whence, for all $n \geqslant N$, we have $\sup_{1 \leqslant j \leqslant k_n}|f(t_j)-f(t_{j-1})| < \epsilon/V_0^1(f),$ and
$$\sum_{j=1}^{k_n}|f(t_j) - f(t_{j-1})|^2 \leqslant \epsilon$$
For something more exotic -- where quadratic variation over partitions  converges to $0$ only for some but not all partition sequences (if such a thing is possible in general) -- you would have to consider continuous functions of unbounded variation.
Comment: If I understood you correctly, you are assuming that $f$ has bounded variation and is uniformly integrable. Can this be deduced or are those additional assumptions?
Comment: I don't know why I cannot edit my further comment, so I will add here that I did not mean "uniformly integrable" but "uniformly continuous". My fault.
Comment: Comments get locked and cannot be edited after a few minutes. I assume bounded variation and continuous (as with your hypothesis).  If $f$ is continuous it is also uniformly continuous since $[0,1]$ is compact (closed and bounded).
Answer: So, here is a way that should work.
Let $\varepsilon>0$ and let $\Delta=\{0=t_0,t_1,\dots,t_k=1\}$ be a partition. (We later use the notation $S(\Delta)=\sum_{i=1}^{k}(f(t_i)-f(t_{i-1}))^2$ and $|\Delta|:=\sup_{i=1,\dots,k}{|t_i-t_{i-1}}|$). We can find a partition $\tilde{\Delta}\supset \Delta$ such that $|\tilde{\Delta}|\leq \varepsilon$. For this partition, we want to construct a further partition $\Delta_{\varepsilon}$ such that $\Delta_{\varepsilon}\supset \tilde{\Delta}$ and $S(\Delta_{\varepsilon})<\varepsilon$. By the continuity of $f$ and the intermediate value theorem, we can find $s_i\in(t_{i-1},t_i)$ such that $f(s_i)=\frac{1}{2}(f(t_{i-1})+f(t_i))$. Hence we obtain a new partition $\bar{\Delta}$ with $|\bar{\Delta}|<\varepsilon$ and $S(\bar{\Delta})=\frac{1}{2}S(\tilde{\Delta})$. Now we repeat the last step until we obtain the desired result.
Note: I never used $f(0)\neq f(1)$ although it was given in the exercise.
Comment: I think my idea (two years ago) was, that if we have $\tilde{\Delta}=\{t_0,t_1,\dots, t_k\}$ and $\bar{\Delta}=\{t_0, s_1, t_1,s_2\dots,s_k, t_k\}$, then $S(\bar{\Delta})=\sum_{i=1}^k((f(s_i)-f(t_{i-1}))^2+(f(t_{i+1})-f(s_i))^2)$ and each summand should be $\frac{1}{2}(f(t_i)-f(t_{i-1}))^2$.
Comment: How do you obtain $S(\bar{\Delta})=\frac{1}{2}S(\tilde{\Delta})$? Maybe I am misunderstanding your construction, because when I write it out I get $S(\bar{\Delta})=\frac{3}{2}S(\tilde{\Delta})$.


How find the range of $m$

Question: Let  $m$ be a positive integer and let

$$I_{m}(x,y)=\sum_{k=0}^{m-1}(e^{\cos{(x-y+2k\pi/m)}}-e^{\cos{(-x-y+2k\pi/m)}})$$
  for all $x,y\in [0,\dfrac{\pi}{m}]$. For which $m$ is $I_m(x,y) \ge 0$?

This problem is from a question my friend asked me, and my friend told me he used MaTLAB and found that it's true for for $m\le 12$. Thank you everyone.
My attempt: I want to find this sum
$$\sum_{i=0}^{m-1}e^{\cos{i\pi}}$$
but I can't it.
Comment: @math110, please do not destroy useful content in this site.
Comment: What happened to Jack D'Aurizio solution? What happened to your problem? The edit history is there. **Please** don't vandalize your questions and **even less** other people answers to it.
Comment: Why did you delete most of your question?
Comment: Why did you delete the content of the question?
Comment: I think it maybe for all $m\in N^{+}$ true? It's nice problem
Comment: Is there $i$ in your original sum?
Comment: I plotted some of these for various $m$'s and you can see that they are $\ge 0$ so they most likely not have $i$ in them. The later sum in the individual's attempt has index $i$ so it could be misleading.
Comment: The sum you tried to find is $\frac{\left\lfloor \frac{m}{2}\right\rfloor }{e}+e \left\lfloor \frac{m-1}{2}\right\rfloor +e$ according to Mathematica.
Comment: @ftfish: the equality comes from the fact that $e^x=\sum_{j=0}^{+\infty}\frac{x^j}{j!}$ and $\sum_{i=0}^{m-1}\cos(i \pi)^k$ is equal to $m$ when $k$ is even an to $\frac{1}{2}(1-(-1)^m)$ when $k$ is odd.
Comment: possible duplicate of [(Closed, Concave, Orientable) Polytope Volume](http://math.stackexchange.com/questions/25491/closed-concave-orientable-polytope-volume)
Answer: UPDATE: This is now a complete solution for even values of $m$.
A really interesting phenomenon is the following: if $k<m$, the values of the sums
$$\sum_{j=0}^{m-1}\sin^k\left(\tau+\frac{2\pi j}{m}\right),\qquad \sum_{j=0}^{m-1}\cos^k\left(\tau+\frac{2\pi j}{m}\right)$$
do not depend from $\tau$, and are exactly equal to the values of
$$\frac{m}{2}\int_{0}^{2\pi}\sin^k(x)\,dx,\qquad \frac{m}{2}\int_{0}^{2\pi}\cos^k(x)\,dx.$$
Moreover, if $k$ is odd the sum $\sum_{j=0}^{m-1}\cos^k\left(\tau+\frac{2\pi j}{m}\right)$ clearly vanishes. By expressing $e^{\cos z}$ as:
$$e^{\cos z}=\sum_{j=0}^{+\infty}\frac{\cos^j(z)}{j!},$$
we get:
$$I_m(x,y)=\sum_{j\geq m/2}\frac{1}{(2j)!}\sum_{k=0}^{m-1}\left(\cos^{2j}\left((x-y)+\frac{2k\pi}{m}\right)-\cos^{2j}\left((x+y)-\frac{2k\pi}{m}\right)\right),$$
and we only need to find appropriate bounds for the difference
$$\sum_{j=0}^{m-1}\cos^k\left(\tau+\frac{2\pi j}{m}\right)-\frac{m}{2}\int_{0}^{2\pi}\cos^k(x)\,dx$$
when $k$ is even and greater or equal to $m$.
By considering the Fourier series of $\cos^{2j}(x)$ we get:
$$I_m(x,y)=4m \sum_{j\geq m/2}\frac{1}{4^j(2j)!}\sum_{h\in[1,j-1]:m|2h}\binom{2j}{j-h}\sin(2hx)\sin(2hy)$$
Now switching sums we have:
$$I_m(x,y)=4m\sum_{r=1}^{+\infty}\sin(rmx)\sin(rmy)\sum_{j\geq 1+rm/2}\binom{2j}{j-rm/2}\frac{1}{4^j(2j)!}$$
and the first term of the sum is clearly positive. By studying how fast the decay of
$$ c_r = \sum_{j\geq 1+rm/2}\binom{2j}{j-rm/2}\frac{1}{4^j(2j)!} $$
is, we should quite easily deduce the positivity of $I_m(x,y)$.
$c_r$ can be expressed in terms of Bessel functions:
$$ c_r = I_{rm}(1)-\frac{1}{2^{rm}(rm)!} = -\frac{1}{2^{rm}(rm)!}+\frac{1}{\pi}\int_{0}^{\pi}\cos(rmx)\,e^{\cos x}dx. $$
Since $\sin(rmx)\sin(rmy)\geq -r^2 \sin(mx)\sin(mx),$ a crude estimation is:
$$ I_m(x,y) \geq 4m\left(\sum_{j\geq 1+m/2}\binom{2j}{j-m/2}\frac{1}{4^j(2j)!}-\sum_{r\geq 2}\sum_{j\geq 1+rm/2}\binom{2j}{j-rm/2}\frac{r^2}{4^j(2j)!}\right)\sin(mx)\sin(my),$$
or, in a more readable form,
$$ I_m(x,y) \geq 4m\sin(mx)\sin(my)\left(c_1-\sum_{r\geq 2}r^2\,c_r\right), $$
so, if we prove
$$\quad\sum_{r=1}^{+\infty}r^2\, c_r \leq 2 c_1,\tag{$\heartsuit$} $$
the claim follows. Since:
$$ c_r = \sum_{h=1}^{+\infty}\frac{1}{4^h\,h!\,2^{rm}\,(h+rm)!}, $$
it is sufficient to prove that for any $h,m\geq 1$
$$\quad\sum_{r=2}^{+\infty}\frac{r^2}{2^{rm}}\cdot\frac{(h+m)!}{(h+rm)!}\leq\frac{1}{2^m}\tag{$\spadesuit$}$$
holds, then summing over $h$ we have that $(\heartsuit)$ holds, too. Now:
$$\sum_{r=2}^{+\infty}\frac{r^2}{2^{rm}}\cdot\frac{(h+m)!}{(h+rm)!}\leq \sum_{r=2}^{+\infty}\frac{r^2}{2^{rm}}\cdot\frac{1}{(h+rm)(h+rm-1)}\leq \sum_{r=2}^{+\infty}\frac{r^2}{2^{rm}}\cdot\frac{1}{r^2 m^2}\leq\frac{2}{m^2\,4^m},$$
so $(\spadesuit)$ holds and $(\heartsuit)$ holds, too.
Hence we have proved that $I_m(x,y)\geq 0$ for any even $m$, and the argument only needs minor adjustments in order to work for odd values of $m$, too.
Comment: What happened to Jack D'Aurizio solution? What happened to your problem? The edit history is there. **Please** don't vandalize your questions and **even less** other people answers to it.

How find the range of $m$


Why does function return false after checking only one value in loop

Question: Trying to check if a value exists within an array, but my nested if statement is returning
false even if the value exists in the array. This worked until I added an else to my loop, now it only works if the value to check for is the first index.

var num = [1, 2, 3, 4, 5, 6, 7, 8, 9];
var inp = parseInt(prompt("Enter a number to see if it is in the array:"));

function checkIfInArray(n, anArray) {

  for (var i = 0; i < anArray.length; i++) {
    if (num[i] == n) {
      return true;
    } else {
      return false;
    }
  }
}

console.log(checkIfInArray(inp, num));
Comment: Did you expect the function to `return false;` *multiple times*? How would that work?
Answer: Even though you have the check inside the for-loop, the code inside the for-loop runs only once because now that you've added an else, it will ALWAYS return something.
The correct way to return false if nothing was found, would be to add the return false after the for-loop finishes.
for(var i = 0;i < anArray.length;i++)
{
     if(num[i] == n)
     {
          return true;
     }
}

return false;

Answer: Your function will stop & exit at the first "return". If you add a return false after the loop, it will ensure that if the function haven't been exited after the loop (= not in array), it will return false :

var num = [1,2,3,4,5,6,7,8,9];
var inp = parseInt(prompt("Enter a number to see if it is in the array:"));

function checkIfInArray(n,anArray)
{
    for(var i = 0;i < anArray.length;i++)
    {
        if(num[i] == n)
        {
            return true;
        }
    }

    return false;
}

var result = checkIfInArray(inp,num);
console.log(result)
Answer: You should use this:
    function checkIfInArray(n,anArray)
    {
        for(var i = 0;i < anArray.length;i++)
        {
            if(num[i] == n)
            {
                return true;
            }
        }
        return false;
    }

Answer: You have an if statement to return at first check, whether true or false
Answer: I came across a similar problem while doing my react app.
We can use Array.some(), this will return true if atleast one condition is true.

const array = [1, 2, 3, 4, 5];

const twoExists = array.some(value => value === 2)
console.log(twoExists)
// expected output: true


Copiar texto de uma textbox

Question:
Como posso fazer para que o botão "Copiar" copie todo o texto da textbox?
Comment: Visual Basic 6 e Visual Basic .NET são linguagens distintas, em qual delas queria sua resposta?
Comment: Visual Basic .NET, não sabia que eram distintas.
Answer: Pelo que entendi é para copiar para área de transferência, então é assim no VB:
Clipboard.SetText(Text1.Text)

onde Text1.text é seu texto
Comment: Exato! Obrigado. ^^
Answer: Private Sub Command1_Click()
txt.SelStart = 0
txt.SelLength = Len(txt.Text)
txt.SetFocus
Clipboard.Clear
Clipboard.SetText Screen.ActiveControl.SelText
End Sub
Answer: Esse é bem simples:
<button type="button"id="MY_ID" data-clipboard-text="Texto de Exemplo" class="btn btn-link">Copiar</button>

Comment: Tão simples que errou.

Copiar texto de uma textbox


Editable ComboBox FXML default value

Question: There is a way how to set default value to ComboBox on JavaFx fxml.
I found sulution here:
https://stackoverflow.com/a/14436371/1344424
<ComboBox editable="true">
    <items>
        <FXCollections fx:factory="observableArrayList">
            <String fx:value="NVT" />
            <String fx:value="Bezig" />
            <String fx:value="Positief" />
            <String fx:value="Negatief" />
        </FXCollections>
    </items>
    <value>
        <String fx:value="NVT" />
    </value>
</ComboBox>

But it not working when Editable property set to true.
How can I set default value to editable ComboBox?
Answer: It seems to work if you set the value via an attribute, instead of an element:
<ComboBox editable="true" value="NVT">
    <items>
        <FXCollections fx:factory="observableArrayList">
            <String fx:value="NVT" />
            <String fx:value="Bezig" />
            <String fx:value="Positief" />
            <String fx:value="Negatief" />
        </FXCollections>
    </items>

</ComboBox>

It also works this way if you pass in a reference to the same string:
<ComboBox editable="true" value="$defaultSelection">
    <items>
        <FXCollections fx:factory="observableArrayList">
            <String fx:id="defaultSelection" fx:value="NVT" />
            <String fx:value="Bezig" />
            <String fx:value="Positief" />
            <String fx:value="Negatief" />
        </FXCollections>
    </items>

</ComboBox>

Comment: All works! Interesting thing. When I put `value="$defaultSelection"` before `editable="true"`, nothing works.
Answer: I fear this is not possible with FXML, but in Java code:
ComboBox<String> combobox = new ComboBox<>(FXCollections.observableArrayList("1","2","3","4","5"));
combobox.setEditable(true);
combobox.getSelectionModel().selectFirst();

Or if you want to select a specific value:
combobox.getSelectionModel().select("3");

Editable ComboBox FXML default value


upper bound for the series $S (x) = \sum_{k=1}^{\infty} \frac{(x_n-n)^k}{k!}$ from $|x_n -(n+1)|\leq x$.

Question: I've been trying to find a tight upper bound for the series
$$S (x) = \sum_{k=1}^{\infty} \frac{(x_n-n)^k}{k!}$$
in terms of finite value $x\in \mathbb R$, where:
1- $\{x_n\}$ is a sequence of a real numbers.
2- $|x_n -(n+1)|\leq x$.
I think that the solution of the problem steps for expansion in Taylor series of
$$e^x = \sum_{k=0}^{\infty} \frac{x^k}{k!}$$
The difficulty of the problem lies in the fact that, while within the series there is the term $(x_n-n)^k$, the condition (2) is on $|x_n -(n+1)|$.
Answer: Hint
I suppose that you are very close since $$S (x) = \sum_{k=1}^{\infty} \frac{(x_n-n)^k}{k!}=\sum_{k=0}^{\infty} \frac{(x_n-n)^k}{k!}-1=e^{(x_n-n)}-1$$
Answer: I would just write
$$
|S(x)| = |e^{x_n-n}-1| =|e^{(x_n-(n+1))+1}-1| \leq e^{|(x_n-(n+1))+1|}-1\leq e^{|x_n-(n+1)|+1} -1\leq e^{|x|+1}-1
$$
Observe that $|x|=x$ in your question.


issue with java script functions

Question: I am adding two text boxes using function and want to display result in third text box. For this I used two functions. First getdata() to read first textbox value and second is getdata1() to read second textbox value. I also use onchange event. but in result it display NaN. Please, help me.
Here is my Code

var a, b, c;

function getdata(txt) {
  x = txt.value;
  if (!isNaN(x)) {
    a = parseInt(document.getElementById("txt").value);
  } else {
    alert("Input not valid");
    txt.focus();
    txt.value = "";
  }
}

function getdata1(txt) {
  x = txt.value;
  if (!isNaN(x)) {
    b = parseInt(document.getElementById("txt").value);
  } else {
    alert("Input not valid");
    txt.focus();
    txt.value = "";
  }
}

function myFunction(s, t) {
  var s = a;
  var t = b;
  var c = s + t;
  document.getElementById("result").value = c;
}
<input type="text" name="txt[]" id="txt[]" onchange="getdata(this)" />
<input type="text" name="txt[]" id="txt[]" onchange="getdata1(this)" />
<input type="text" name="result" id="result" onfocus="myFunction()" />
Comment: write question and code in proper format and provide your html code
Comment: https://stackoverflow.com/help/how-to-ask

Read this!! and edit your question.
Comment: you have given both text boxes with same `id` which is one of the reason for the error
Answer: Do not use same id values for different element! Use x values instead of document.getElementById("txt").value.

var a, b, c;
function TryParceData(src, old) {
  x = src.value;
  if (!isNaN(x)) {
    return parseInt(x);
  } else {
    alert("Input not valid");
    src.focus();
    src.value = "";
    return old;
  }
}
function getdata(txt) {
  a = TryParceData(txt, a);
  myFunction();
}

function getdata1(txt) {
  b = TryParceData(txt, b);
  myFunction();
}

function myFunction(s, t) {
  var s = a;
  var t = b;
  var c = s + t;
  document.getElementById("result").value = c;
}
<input type="text" name="txt[]" onchange="getdata(this)" />
<input type="text" name="txt[]" onchange="getdata1(this)" />
<input type="text" name="result" id="result" onfocus="myFunction()" />
Comment: Thankx for this lovely solution. problem is solved but one more thing is that when onchange event occur in text2 then result show. means reflection should be done from both text boxes. plz help for this also.
Comment: @VishalGoyal, l did not understatnd. Do you want to show result in `#result` input when first or second input is changed?
Comment: @VishalGoyal, append `myFunction();` line into both `getdata()` and `getdata1()` functions. I have made corresponding changes of my code.
Answer: first of all, if you have multiple element that has the same ids, the first or last will be the only one fetched by your selector. Second, attribute 'id' is called id because it gives identity to your element, which basically means try not to give same identity to each elements. Third, you're getting NaN because you're looking for an element with id 'txt' but there is none in your page (this error occurs in your parseInt part). The id of your element is 'txt[]'. Try changing those ids to 'txt1' and 'txt2' for the other one and change your scripts. Update me when you've fixed it. cheers
Answer: try this code

var a, b, c;

function getdata(txt) {
  x = parseInt(txt.value);
  if (!isNaN(x)) {
    a = parseInt(document.getElementById("txt").value);
  } else {
    txt.focus();
    txt.value = "";
  }
}

function getdata1(txt) {
  x = parseInt(txt.value);
  if (!isNaN(x)) {
    b = parseInt(document.getElementById("txt1").value);
  } else {
    txt.focus();
    txt.value = "";
  }
  myFunction();
}

function myFunction() {
  var c = a + b;
  document.getElementById("result").value = c;

}
<input type="text" id="txt" onblur="getdata(this)">
<input type="text" id="txt1" onblur="getdata1(this)">
<input type="text" id="result">

issue with java script functions


Evaluating a definite integral using residue theorem

Question: I am trying to show $$\int_0^{\infty} \frac{\log (x)}{(x^2+1)^2}$$. We can use the integrand $g(z) = \frac{\log(z)}{(x^2+1)^2}$ defining log as $\log(\rho e^{i\theta}) = \log(\rho) + i\theta$ and letting $\theta \in [0,2\pi]$
Now, I know that the singularities of the integrand occur at $i,-i$ one being in the upper half plane, the other in the lower half plane.
Typically the counter used for integrands which require choosing a branch cut of log is a half donut shape on the upper plane. Since there is a singularity no on the lower half plane, do I ignore it or include the residue of it in the calculation?
Also, I believe the singularities to be poles of order 3 and I do not know how to calculate residues for them. Is there an explicit formula like there is for simple poles?
Answer: You are trying to show... what?
$$\begin{eqnarray*}\int_{0}^{+\infty}\frac{\log(x)}{(1+x^2)^2}\,dx &=& \int_{0}^{1}\frac{\log x}{(1+x^2)^2}\,dx+\underbrace{\int_{0}^{1}\frac{-x^2\log(x)}{(1+x^2)^2}\,dx}_{x\mapsto 1/x}\\&=&\int_{0}^{1}\frac{1-x^2}{(1+x^2)^2}\log(x)\,dx\end{eqnarray*} $$
and since $$\forall x\in(0,1),\qquad \frac{1-x^2}{(1+x^2)^2}=\sum_{n\geq 0}(-1)^n (2n+1) x^{2n}, $$
$$ \int_{0}^{1}x^{2n}\log(x)\,dx = -\frac{1}{(2n+1)^2}$$
we have:
$$ \int_{0}^{+\infty}\frac{\log x}{(1+x^2)^2}\,dx = -\sum_{n\geq 0}\frac{(-1)^n}{2n+1}=-\arctan(1)=\color{red}{-\frac{\pi}{4}}.$$
We do not strictly need Complex Analysis.
Answer: Any singularity outside the contour will be irrelevant to the integral.
The poles in this case will be of order $2$.  A residue for a pole of order at most $m$ can be found from
$$Res(f,z_0)=\frac1{(m-1)!}\lim_{z\to z_0}\frac{d^{m-1}}{dz^{m-1}}(z-z_0)^mf(z)$$
which for large $m$ can be frustrating but should be OK in this case.
Comment: Ah yes, you are right that it is a pole of order 2, thank you for catching my mistake!
Comment: so would I have $$Res(g,z_0) = \lim_{z \rightarrow i} 2(z-z_0) [\frac{(z^2+1)^2}{z}-log(z)4z(z^2+1)]\frac{1}{(z^2+1)^3}$$ and if so wouldnt this limit be zero?
Comment: I can't follow your differentiation.  Remember that in this case $z_0=i$, and that $$(z-z_0)^2f(z)=\frac{(z-i)^2}{(z^2+1)^2}\log z\ ,$$ simplify first then differentiate.  The answer might be zero, I haven't worked it out.