matplotlib scale axes according to arbitrary function

Question: I am plotting a 5th degree polynomial... for simplicity, lets just go with y=(x-3)(x-2)x(x+2)(x+3).  On reasonable intervals for x, say from -5 to 5, the graph isn't very informative because the function grows very quickly outside of the "interesting" range, about -3 to 3:

A symlog scale is somewhat better, but now I'm looking at the log of a 5th degree polynomial, which is a bit hard for me to interpret:

Ideally, I could plot this on a polynomial scale.  Since I know I have a 5th degree polynomial, then a 5th root scale would be able to fit all of my data, and the graph should behave linearly out near the edges.  Is it possible to scale my axes with an arbitrary function?
Answer: I adjusted this example as follows:
import numpy as np
import matplotlib.pyplot as plt

y = np.random.normal(loc=0.5, scale=0.4, size=1000)
x = np.arange(len(y))

fig, ax = plt.subplots(figsize=(6, 8), constrained_layout=True)

t = np.arange(1, 170.0, 0.1)
s = t / 2.

ax.plot(t, s, '-', lw=2)
ax.set_yscale('function', functions=(lambda x: x**5, lambda x: x**(0.2)))
ax.grid(True)
ax.set_ylim(0,5)
plt.show()

Comment: I'm surprised that really worked.  You don't want xaxis and yaxis, your want forward and inverse `functions=(lambda x: x**5, lambda x: x**(0.2))`


selected dropdown list value changes after page reload

Question: I have a dropdown list in my application's layout . So in every page it is visible . In the dropdown list I have a list of hotels , when I change a hotel in dropdown , it redirects to the main page , with the changed id , it works fine , but the problem is when reloading the page , selected dropdown value is reset , how can i keep the selected value with out changing? . :(
Comment: i am using zend framework ......
Answer: You'd need to store its state somewhere, perhaps in a cookie.
Then on page load, you'd need to retrieve its state on load.
Comment: yeah i stored current value in a seesion and passed to the form when creating the form thanksssssss


Proving the inequality $|x|^2 + |y|^2 < 1 + |xy|^2$ for $x, y \in B_1(0) \subset \mathbb{C}$

Question: Let $x, y \in B_1(0)\subset \mathbb{C}$. I am trying to show that $|x|^2 + |y|^2 < 1 + |xy|^2$. This is an inequality that I should be able to prove, but apparently I am unable to do so in a rigorous way. My work so far is the following:
We can write the expression as
$$1 - |x|^2\left(1 - |y|^2\right) - |y|^2 > 0$$
which represents a parabola after the variables have been converted so real ones, as $|x| \in [0, 1)$, we do not really care about the complex properties of the numbers. We can see that the polynomial has two roots, namely at $x = \pm 1$ (in terms of x) and these are all the roots of the polynomial. Since the highest order monomial has a negative coefficient, the parabola opens down and hence it has to be positive on $|x| \in [-1, 1]$.
You might see what I meant with unable to do so in a rigorous way, since this argument relies on the intuitive properties of parabolas from HS level mathematics.
(Question:) So, how could one massage the expression to prove the strict inequality (or even inequality in the case that $x, y \in \overline{B_1(0)}$)?
Comment: Maybe your method may have some flow in the reasoning (too tired to check) but why should not it be rigorous? The convex shape of a parabola, position of maxima, minima,... are not something intuitive but rigorous facts that one can exploit
Answer: $|x|^2 + |y|^2 < 1 + |xy|^2$ is equivalent to
$$
 0 < (1-|x|^2)(1-|y|^2)
$$
and that is true for all $x, y \in B_1(0)$ since both factors on the right are strictly positive.
For $x, y \in \overline{B_1(0)}$ the same argument shows that $|x|^2 + |y|^2 \le 1 + |xy|^2$.


jquery plugin multiple instances

Question: I'm trying to create a simple jQuery plugin that allows for multiple instances of a "timepicker".  I haven't done much JavaScript OOP in the past so I figured that create this would be an excellent learning experience for me.  That being said, I cannot seem to figure out why all instances are affected when I changed the time.  This is my first post on StackOverflow so please bear with me.
Here's the code:

(function($) {

  //Helper functions
  if (typeof String.prototype.endsWith != 'function') {
    String.prototype.endsWith = function(str) {
      return str.length > 0 && this.substring(this.length - str.length, this.length) === str;
    }
  }

  //Find if area is on the clickable list
  var findOne = function(haystack, arr) {
    return arr.some(function(v) {
      return haystack.indexOf(v) >= 0;
    });
  };

  var Timepicker = function(element, options) {

    this.defaults = {
      now: new Date()
    };
    this.element = $(element);
    this.createTimepicker();
    this.options = $.extend({}, this.defaults, options);
    this.timepicker = $('.wicked-picker'); //The outer portion of the picker
    this.up = $('.wicked-picker__controls__control-up'); //the up control(s)
    this.down = $('.wicked-picker__controls__control-down'); //the down control(s)
    this.hoursElem = $('.wicked-picker__controls__control--hours'); //the hours text
    this.minutesElem = $('.wicked-picker__controls__control--minutes'); //the minutes text
    this.meridiemElem = $('.wicked-picker__controls__control--meridiem'); //the am or pm text
    this.canClick = ['timepicker', this.timepicker.selector.substring(1), this.up.selector.substring(1), this.down.selector.substring(1), this.hoursElem.selector.substring(1), this.minutesElem.selector.substring(1), this.meridiemElem.selector.substring(1)]; //the clickable areas
    this.selectedHour = ((this.defaults.now.getHours() + 11) % 12) + 1; //the default hour
    this.selectedMin = ((this.defaults.now.getMinutes() < 10) ? '0' : '') + this.defaults.now.getMinutes(); //the default minute
    this.selectedMeridiem = (this.defaults.now.getHours > 12) ? 'PM' : 'AM'; //the defaut meridiem
    this.attach(element); //attach events to this element

  };

  $.extend(Timepicker.prototype = {

    showTimepicker: function(element) {
      var timepickerPos = this.element.offset();
      //set time to default time (now)
      this.setText(element);
      //if the timepicker's time differs from the input field's time change it
      if (this.getText(element) !== this.getTime()) {
        var inputTime = this.getText(element).replace(':', '').split(' ');
        var newTime = new Date();
        newTime.setHours(inputTime[0]);
        newTime.setMinutes(inputTime[2]);
        this.setTime(newTime);
      }
      //Positioning
      this.timepicker.css({
        'z-index': this.element.zIndex() + 1,
        position: 'absolute',
        left: timepickerPos.left,
        top: timepickerPos.top + element.target.offsetHeight + 5
      }).show();

      //Time up/down events
      //Most likely the area with issues
      //Needs to know which instance
      $(this.up).on('click', $.proxy(this.changeValue, this, '+', element));
      $(this.down).on('click', $.proxy(this.changeValue, this, '-', element));
    },

    hideTimepicker: function(element) {
      var targetClass = element.target.className.split(' ');
      //Check if area is clickable before hiding
      if (findOne(targetClass, this.canClick) === false) {
        this.timepicker.hide();
      }
    },

    //Create only one timepicker per page
    createTimepicker: function() {
      if ($('.wicked-picker').length === 0)
        $('body').append('

Timepicker

 00

 00

 AM

');
    },

    //Attach the show and hide picker events
    attach: function(element) {
      $(element).on('focus', $.proxy(this.showTimepicker, this));
      $('body').on('click', $.proxy(this.hideTimepicker, this));
    },

    //set the timepicker's time
    setTime: function(time) {
      this.setHours(time.getHours());
      this.setMinutes(time.getMinutes());
      this.setMeridiem();
    },

    //get the timepicker's time in the form H : MM : AM || PM
    getTime: function() {
      return [this.getHours + ' : ' + this.getMinutes() + ' ' + this.getMeridiem()];
    },

    //set the timepicker's and input field's hours
    setHours: function(hours) {
      var hour = new Date();
      hour.setHours(hours);
      var hoursText = ((hour.getHours() + 11) % 12) + 1;
      this.hoursElem.text(hoursText);
      this.selectedHour = hoursText;
    },

    //set the timepicker's hours
    getHours: function() {
      var hours = new Date();
      hours.setHours(this.hoursElem.text());
      return hours.getHours();
    },

    //set the timepicker's and input field's minutes
    setMinutes: function(minutes) {
      var minute = new Date();
      minute.setMinutes(minutes);
      var minutesText = minute.getMinutes();
      var min = ((minutesText < 10) ? '0' : '') + minutesText;
      this.minutesElem.text(min);
      this.selectedMin = min;
    },

    //set the timepicker's minutes
    getMinutes: function() {
      var minutes = new Date();
      minutes.setMinutes(this.minutesElem.text());
      var minutesText = minutes.getMinutes();
      return ((minutesText < 10) ? '0' : '') + minutesText;
    },

    //set the timepicker's and input field's meridiem
    setMeridiem: function() {
      var meridiem = this.getMeridiem();
      var newMeridiem = (meridiem === 'PM') ? 'AM' : 'PM';
      this.meridiemElem.text(newMeridiem);
      this.selectedMeridiem = newMeridiem;
    },

    //set the timepicker's meridiem
    getMeridiem: function() {
      return this.meridiemElem.text();
    },

    //change the input field's time based on the arrow selected for each time unit
    //input is the input field to be changed
    //element is the up or down arrow clicked
    //operator is the '+' or '-' sign
    changeValue: function(operator, input, element) {
      var target = (operator === '+') ? element.target.nextSibling : element.target.previousSibling;
      var targetClass = $(target).attr('class');
      if (targetClass.endsWith('hours')) {
        this.setHours(eval(this.getHours() + operator + 1));
      } else if (targetClass.endsWith('minutes')) {
        this.setMinutes(eval(this.getMinutes() + operator + 1));
      } else {
        this.setMeridiem();
      }
      console.log('changed ' + $(input.target).attr('name'));
      this.setText(input);
    },

    //Set the input field's time
    setText: function(input) {
      console.log('set ' + $(input.target).attr('name') + ' to ' + this.selectedHour + ' : ' + this.selectedMin + ' ' + this.selectedMeridiem);
      $(input.target).val(this.selectedHour + ' : ' + this.selectedMin + ' ' + this.selectedMeridiem);
    },

    //Get the input field's time
    getText: function(input) {
      return $(input.target).val();
    }

  });

  //Create timepickers
  $.fn.timepicker = function(options) {
    return this.each(function() {
      new Timepicker(this, options);
    });
  };

}(jQuery));
<!DOCTYPE html>

  <meta charset="UTF-8">
  <title></title>

  <input type="text" name="event-start-time" id="event-start-time" class="form-input timepicker grid-5" />
  <input type="text" name="event-end-time" id="event-end-time" class="form-input timepicker grid-5" />

Comment: Does it still do it if you change it to `$('.timepicker').timepicker();` ? You are passing in an empty array not an object. Not sure if it matters, but it's strange none the less.
Comment: Sorry, in my actual code it has an empty object. It only represents a possible list of future options. In other words yes it still does it.
Comment: "*`//Create only one timepicker per page`*" is not exactly like allowing multiple instances. All your `Timepicker` instances reference the same DOM element. Is that expected?
Comment: @Bergi When I say a single timepicker I mean that I only want one to generate a single picker that multiple inputs can use. Kind of like how you can use the same jQuery UI datepicker calendar on multiple inputs
Comment: @EricGagnon: Yes, but your `TimePicker`s all do attach their event handlers on the same DOM element, and so one event affects all inputs. You'll need to have a static variable that tells *whether and on which input* the timepicker is currently active.
Comment: @Bergi I see what you mean. Do you have any suggestions about how to go about it?
Answer: I was able to solve the problem by removing the previous up and down event click event handlers and then reapplying the new click event handlers.  This was accomplished by changing
$(this.up).on('click', $.proxy(this.changeValue, this, '+', element));
$(this.down).on('click', $.proxy(this.changeValue, this, '-', element));

to
$(this.up).off('click').on('click', $.proxy(this.changeValue, this, '+', element));

$(this.down).off('click').on('click', $.proxy(this.changeValue, this, '-', element));

Thanks for all the advice!

jquery plugin multiple instances


Can't get Nginx to serve correct certificate chain


What must the file permissions be for x-sendfile to work with apache

Question: I have a Ruby-on-Rails application that I am hosting with Apache and Phusion-Passenger (on Ubuntu Server). In this app I have a controller method that basically protects access to some files based on the currently logged in user and then servers them using X-sendfile. The method looks something like this:
def show
     if File.exists @file_name
         sendfile @file_name, :xsendfile => true
     else
         render_404
     end
end

It mysteriously does not work on our staging server and I suspect It has something to do with file permissions because every time I hit it I get a 404 but it is not the 404 page that my would render as a result of my render404 call; thus I suspect the error is occurring after the sendfile line is executed.
Could someone please clarify for me what must the file permissions be in order for apache to server something via x-sendfile.
PS I should also point out that I am quite sure that my X-sendfile module is properly configured and working so its nothing to do with that
Answer: As always, it must be readable by the user the web server is running as.
Comment: Ya this should have been obvious... In the end the problem was that the group Apache was running as was not what I expected. I just learned about the envvars file... :s


Are these tables in the third normal form?

Question: I have decomposed a relationship that tracks employee's and the hours they have spent working at hotels. The original relationship is as follows
R(national insurance number, contract Number, hours, eName, hotel Number,     hotel Location)

rewritten as
R(A, B, C, D, E, F)

I have found the Functional dependencies
F:(A->D, E->F, AB->C, B->E, BA->E)

From this I have created the following 3 tables
1.
Employees:
national insurance number(A)
eName(D)
PRIMARY KEY(A)

2.
Works at:
contract Number(B)
Hours(C)
national insurance number(A)
PRIMARY KEY(B, AND A)

3.
Hotel:
contract Number(B)
hotel Number(E)
hotel Location(F)
PRIMARY KEY(B)

In my third table, I have a primary key that can determine both the number, and location of the hotel. But the hotel number can also determine the hotel
location.  Should I move the hotel location to a new table, with only hotel number?  That would use more space, but is it necessary to reach the 3RD normal form?
Comment: Is the contract number in the 'works at' table the same contract number in the 'hotel' table?
Comment: I would expect contract to be its own table, with the works at table linking employees to contracts.  If a hotel can have one and only one contract, then the contract number would be in a hotel, but what about cases where a contract expires or a hotel can have multiple contracts.  In that case, there would be a hotel-contract linkage table governing those terms.
Comment: It seems unlikely your contract number would be the PK in your hotel table in any case.
Comment: What is a *definition* of 3NF? What does it tell you about your decomposition? Why did you decompose this way? What reference are you using to decompose?
Answer: When assuming that the FDs you derived are correct and complete, to achieve 3rd normal form in your setting, it is in deed necessary to split Hotel(B,E,F) { B->E, E->F } into HotelContract(B,E) { B->E } and Hotel(E,F) { E->F }.
Formally, in { B->E, E->F }, B is the (sole) key, E is a "non prime" attribute (i.e. is not part of any key), and therefore F depends transitively through a non prime attribute from a key. This violates 3rd normal form.
With a schema Hotel(B,E,F) { B->E, E->F }, which violates 3NF, you get a "deletion anomaly", i.e. you loose more information than necessary when deleting a tuple from Hotel. Suppose the following extension of Hotel:
Hotel
 B | E | F
---|---|---
b1 | e1| f1
b2 | e2| f2

When you delete tuple (b2,e2,f2), then you loose the information that hotel e2 is located in f2, although you just wanted to delete the contract.
Even worse, when you translate the scheme into
Hotel:
contract Number(B)
hotel Number(E)
hotel Location(F)
PRIMARY KEY(B)

then you actually omit FD E->F, which would permit that the same hotel e1 gets two different locations, for example f1 and f2:
Hotel
 B | E | F
---|---|---
b1 | e1| f1
b2 | e1| f2  -> permitted by your scheme, but not intended!

Hence, split the table as recommended in the intro.
Answer: It seems like you are right. Hotel needs to be in separate table.
Also I guess there is a possibility to employee to work on more than one contract in more than one hotel, and one hotel may have more than one contract for employee.
so, to me normalized form will look like:
1. Employees:
   national insurance number(A)
   eName(D)
   PRIMARY KEY(A)

2. Hotels:
     hotel Number(E)
     hotel Location(F)
     PRIMARY KEY(E)

3. Contracts:
    contract Number(B)
    hotel Number(E)
    PRIMARY KEY(B)
    FOREIGN KEY(Hotels.E)

4. Works at:
   work at(G),
   national insurance number(A)
   contract Number(B)
   Hours(C)
   PRIMARY KEY(G)
   FOREIGN KEY(Employees.A)
   FOREIGN KEY(Contracts.B)

Comment: Normalization does not introduce new column names. Also, you were *told* what the FDs are, so your "guess there is a possibility" is inappropriate.


IPMI graceful shutdown before `power cycle` when executing with ipmitool?

Question: I have many servers that sometimes require the entire server to be cold started due to certain changes.
We have many servers so this all is automated.
Right now, if the process requires a cold start, the task runs ipmitool power cycle locally on the host to give it a full cold restart.
This hasn't been a problem, but I can see it being an issue in the future since there is no attempt at a graceful shutdown. I know there is IPMI power soft so it would be nice if there is a way to combine power soft and then power cycle after the soft power down completes OR a timeout elapses.
Is this possible at all? I realize I could do this externally by executing power soft, monitoring, then running a separate power cycle, but that would require connecting to ipmi remotely which is out of scope for this current automation.
Comment: did you done at first the usual things like, update the software, Firmware etc? I mean it could also be a nasty old crappy firmware/Software Bug
Comment: Automated with what? Where is your code?
Comment: @symcbean Ansible, literally just running `ipmi power cycle` (which is in the original post) as a command task but that doesn't change the context or meaning of the question at all. This question is about ipmi behavior.
Comment: You know you can powercycle the server from the remote one using `ipmitool` there, right ? For obvious reason you cannot powerdown and then powercycle certain cerver locally so do it remotely using the same `ipmitool` and the network access to the target IPMI. :)
Answer: Do you really have to use just a single command for that? Sequence like that
CREDS="-H <host> -U <user> -P <passwd> -I lanplus"
ipmitool $CREDS power soft
while [ $(ipmitool $CREDS power status)="on" ]; do
  sleep 1
done
ipmitool power on

will do what you need imho. Of course some timeout should be taken into account to ensure rebooting if OS hangs.


After normalising my data using DataPreparer while using random forest and SVM, why do my data values become negative?

Question: I am working on predictive modeling where I need to predict whether an online customer ends up purchasing a product on a website or not, and I am using Random Forest Classifier and SVM since it's a classification problem.
After creating the fitting splits for training, testing, and validation sets, I dummify, standardize and normalize my data. However, after I normalize the sets, their values become all negative. Is there a way to change that and why does it happen?
The code that I am using to normalize my fitting sets is as below:
<code>data_preparer = DataPreparer(one_hot_encoder, standard_scaler)
data_preparer.prepare_data(fitting_splits.train_set).head()
data_preparer.prepare_data(fitting_splits.validation_set).head()
</code>
Answer: I think the documentation from sklearn.preprocessing.StandardScaler can help here:

The standard score of a sample x is calculated as:
z = (x - u) / s
where u is the mean of the training samples or zero if
with_mean=False, and s is the standard deviation of the training
samples or one if with_std=False.

Based on this equation, if x (the individual value currently being scaled) is less than the mean of the variable, then your scaled value will be negative.


Best book on logic puzzles

Question: I am learning discrete mathematics and to develop logic most people advised me to solve logical puzzles. Can anyone suggest me some good books on logical puzzles?
Comment: There is a wide variety of deductive puzzles similar to Kenken.  Are you looking specifically for puzzles of that style?  (Where the rule set is very small and precisely defined, rather than inferred from general knowledge.)
Comment: I just wanted to be specific among puzzles with math analysis,physics puzzles,computer puzzles etc.
Comment: I'm not so good at Kenken, that can do the job too but i'm looking for questions which should be solved with logic.
Answer: Books by Smullyan come to mind.  For instance, The Goedelian Puzzle Book.
Answer: If you want to have good grip on logical mathematics then I would prefer Ross Honsburger.
Read his collection which mainly consist of 3 volumes of Mathematical Gems and Mathematical circles.

Best book on logic puzzles


Are upper triangular matrices normal subgroup of general linear group

Question: Are the matrices  which are subset of $GL_n(\mathbb{R})$,$\begin{pmatrix} 1&&a_{12}\\0&&a_{22}\end{pmatrix}$ and $\begin{pmatrix} a_{11}&&a\\0&&a\end{pmatrix}$ normal subgroups of $GL_2(\mathbb{R})$?
I tried finding the conjugate of any general invertible matrix with the above matrices but did not get an upper triangular matrix in the end. Any help. Thanks beforehand.
Comment: You're correct that conjugation will sometimes not yield an upper triangular matrix in the end. Since those subgroups are not closed under conjugation (note that the second is not a subgroup unless you ignore the zero matrix), they are not normal subgroups.

It suffices to find one counter-example, and often examples are helpful for understanding a problem anyway. There is no reason to compute a general conjugate when a specific, easily computable example will probably work.
Comment: @user3798897 sorry, modified the post.
Comment: That second set still has the zero matrix. I'm less sure it forms a subgroup anyway though. In fact I'm nearly certain it doesn't.
Comment: @user3798897 ok, what if the sets are subsets of the group $GL_2(\mathbb{R})$?
Comment: They are definitely subsets, but to be a normal subgroup (is that what you want?) you need for the sets to be subgroups which are closed under conjugation. Neither of them are since you can take 'most any matrix in $GL_2(\mathbb{R})$ with positive elements and conjugate 'most any matrix in your sets and get something which is not upper triangular, so definitely not in your sets.
Comment: @user3798897 thanks, by the way you could post that as an answer.
Comment: You're welcome. I'll do that.
Answer: You definitely have subsets, but to be a normal subgroup you need for the sets to be subgroups which are closed under conjugation. Neither of them are since you can take 'most any matrix in $GL_2(\mathbb{R})$ with positive elements and conjugate 'most any matrix in your sets and get something which is not upper triangular, so definitely not in your sets.


Why can't I delete both account and content when cancelling a user account, in Drupal 8?

Question: Before, drupal 7 core, and in drupal 6, a contrib module called user_delete,  had this 4th option in deleting user accounts settings:
"Delete the account and its content." (drupal 7) and
"delete a user and delete all submitted content including nodes and comments" (drupal 6)
But this option seems unavailable in drupal 8 core. Why?
I really want both account and content deleted. The option they offer would force me to periodically delete the unpublished content of the removed account via cron.
Or am I missing something here?
Answer: Deleting content requires an access check, and as such the Delete the account and its content. option can't be selected as the default. I presume this is because a user can have access to cancel their own account, but not be able to select the method, and there's no mechanism implemented to provide a fallback for the default.
You'll still see it when cancelling an individual account, provided you have the administer users permission:

If you'd rather get control of that process yourself you can implement hook_user_cancel_methods_alter to remove or change the access check.
Comment: Absolutely there's a way - remove the access property using the hook. Then it'll be exactly the same as it was in D7. The access check was introduced as a security improvement, if you don't need it you can just get rid of it with a few lines of code, no harm done. If you think it's a regression, just open an issue on the core issue queue. They'll either agree and change it, or (more likely) explain in more detail what the motivation and requirements were for the D8 version
Comment: You are clarifying the existing logical mechanism well, but what I don't understand why this method has been chosen in D8.

Is there no way in D8 to have an auth. user "Delete his account and its content.", without having other cancelling methods, just the button "cancel account"? I mean, by configuration in the admin's interface (I'm sure it's possible by code)

It just seems to such an obvious demand, allowing a user to fully remove himself incl content, that IMHO, it should be configurable in the interface, like in Drupal7 (where I spent like 3 mins on the subject and it just worked).
Comment: I appreciate your help, thanks a lot. I'll just use the hook to override it then. (I'll remove my other "answer").
Comment: It appeared this would not work, because of some batch operation restriction.. When clicking the cancel account link in the confirmation email, a batch screen appears, but frozen.. It said "Initializing", but never starts to actually remove account and nodes.
Comment: Since I did not really wanted to use the email confirmation anyway, I chose to use this module ( https://www.drupal.org/project/user_cancel_immediate ) , which circumvents the batch issue. It is working well now.


find non linear dependencies in the model automatically with Lasso

Question: I have a little knowledge on Lasso, from what i know its pretty good at feature selection and also finds the best sweet spot between bias and variance trade-off. If we are to come up with a regression model from a dataset automatically, we may have features that are not linearly dependent but log of the feature is linearly dependent, in some cases may be sqaure root of the feature is linearly dependent. How do we identify such relationships automatically without assessing the data as the features change dynamically?
If we can find such relationships, Can we pass the sqrt(feature) as a linear value to lasso to find its relevance?
I am new to regression analysis, so please if you could give a detail explanation I highly appreciate it, also please suggest if there is better plan than using lasso?
Answer: Sure, I suppose that you can just throw a huge number of possible features at the model and penalize model complexity using regularization. This seems like a variant of the MARS/EARTH approach that also throws a huge number of possible nonlinear basis functions at the model and figures out which stick.
A big drawback to this is that feature selection is notoriously unstable, and if you do some kind of cross validation or bootstrap, you are likely to find different features being selected, depending on the exact data. What, then, would be the "correct" features for modeling?
The typical suggested resource for learning how to include the kind of flexibility you desire is the textbook Regression Modeling Strategies by Frank Harrell of Vanderbilt University. The gist is that Harrell, who is an active contributor to Cross Validated whose profile you can search for posts on related topics, advocates for flexible models using splines that discover the nonlinear relationships, rather than fitting a particular functional form like a logarithm or a square root.


Three vectors in a plane are linearly dependent?

Question: The 3 vectors $u=(1,2,3)$, $v=(2,5,7)$, $w=(1,3,5)$ are linearly independent. But they should be linearly dependent as they lie on the same plane, then where this concept goes on such type of questions?
Comment: Why do you say that they lie in the same plane?
Answer: It's true that any set of three points is coplanar, but for linear dependence, we only care about planes that pass through the origin, as those are the two-dimensional vector subspaces of $\mathbb R^3$. Those planes are the set of all linear combinations of a pair of linearly-independent vectors, whereas planes that don't include the origin can't be generated that way. So, in the context of linear algebra, the qualifier "through the origin" is often understood and omitted to save space.
Answer: Adding the first row to and subtracting the second row from the third gives
$$
\begin{align}
\det\begin{bmatrix}1&2&3\\2&5&7\\1&3&5\end{bmatrix}
&=\det\begin{bmatrix}1&2&3\\2&5&7\\0&0&1\end{bmatrix}\\[6pt]
&=\det\begin{bmatrix}1&2\\2&5\end{bmatrix}\\[18pt]
&=1
\end{align}
$$
So the three vectors are linearly independent.
Answer: They are not in the same plane.
Three vectors in $\mathbb{R}^3$ are in the same plane if and only if they lie in a 2-dimensional subspace of $\mathbb{R}^3$.
Here they are linearly independent, as you correctly said, so they cannot be inside a 2-dimensional subspace.
Comment: Can u illustrate it with an example,I mean lying vector on plane


Dip-polishing silver-nickel keys

Question: I'm working on restoring an old clarinet. The keys are badly tarnished - I've been working on them using a cloth and metal polish, but:

It's very time consuming;
I'm finding it impossible to get
into all the corners, between the keys and the columns.

Does anyone have any experience with soaking keys, to remove tarnish chemically? I've heard of using a vinegar solution (a test is currently soaking now), and also this method using baking soda and aluminium foil. I'm also trying diet coke, as that's meant to be pretty corrosive.
Does anyone have any better ideas? I'm open to purpose-designed products, but wasn't able to find anything I trusted. Needless to say, a buffing machine, as the professionals appear to use is out of my budget.
Comment: Never tried it on a clarinet - but the baking-soda/foil trick has worked well on other similar materials.
Answer: I trialled all three methods. Both the coke and vinegar solution took some of the tarnish off over about 8 hours, but neither did the entire job. (The coke was more effective, but perhaps using straight vinegar, rather than a solution may help.)
The bicarbonate of soda was the most effective method. An hour or two of soaking took a lot of tarnish off, although left a black residue. (Image 2 below, after a quick wipe.) This polished off with 10 mins of work and metal polish though, giving the effect in the third image below.

To summarise the method for future readers:

Line a container with aluminium foil
Place key on foil, ensuring plenty of key is in contact with foil
Boil enough water to submerge the item
Add Bicarbonate of Soda to the water. [WARNING: Mix will fizz and may overflow, do this in a sink]

The guide recommends 1 cup soda/gallon water. Being British, and not understanding any of these measurements - I guessed.

The guide recommends you may need multiple treatments i.e. reboiling the water. I haven't tried.
Comment: Great stuff! As a guitarist I'm unlikely ever to need to follow this advice, but +1 for providing good, clear information. (And for the "Being British" comment; sums up my attempts at following American recipes…)

Dip-polishing silver-nickel keys


Celery No hostname was supplied. Reverting to default 'localhost'

Question: I have this in my /var/log/celery/w1.log

I'm following the steps for Celery here.
I have this in my celery.py
from __future__ import absolute_import, unicode_literals

import os

from celery import Celery

# Set the default Django settings module for the 'celery' program.
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'sample.settings')

app = Celery('sample2',
            broker='amqp://',
            include=['sample2.tasks'])

# Using a string here means the worker doesn't have to serialize
# the configuration object to child processes.
# - namespace='CELERY' means all celery-related configuration keys
#   should have a `CELERY_` prefix.
app.config_from_object('django.conf:settings', namespace='CELERY')

if __name__ == '__main__':
    app.start()

what can I do to fix this? Thanks in advance.
Answer: Full document in this link.
you should just add the below line to __init__.py near settings.py
from .celery import app as celery_app

__all__ = ['celery_app']

project structure
- proj/
  - manage.py
  - proj/
    - __init__.py
    - settings.py
    - urls.py

Comment: @ryuzakyl
yes of course. this link explained how to config celery in Django. https://docs.celeryq.dev/en/stable/django/first-steps-with-django.html
Comment: Worked! Still would like to know what's happening under the hood here. Any reference to the docs or a PR solving/tackling this particular error?
Comment: # This will make sure the app is always imported when
# Django starts so that shared_task will use this app.
from .celery import app as celery_app

__all__ = ('celery_app',)


What is your strategy to write logs in your software to deal with possible HUGE amount of log messages?

Question: Thanks for your time and sorry for this long message!
My work environment
Linux C/C++(but I'm new to Linux platform)
My question in brief
In the software I'm working on we write a LOT of log messages to local files which make the file size grow fast and finally use up all the disk space(ouch!).  We want these log messages for trouble-shooting purpose, especially after the software is released to the customer site.  I believe it's of course unacceptable to take up all the disk space of the customer's computer, but I have no good idea how to handle this.  So I'm wondering if somebody has any good idea here.  More info goes below.
What I am NOT asking
1). I'm NOT asking for a recommended C++ log library.  We wrote a logger ourselves.
2). I'm NOT asking about what details(such as time stamp, thread ID, function name, etc) should be written in a log message.  Some suggestions can be found here.
What I have done in my software
I separate the log messages into 3 categories:

SYSTEM: Only log the important steps in my software.  Example: an outer invocation to the interface method of my software.  The idea behind is from these messages we could see what is generally happening in the software.  There aren't many such messages.
ERROR: Only log the error situations, such as an ID is not found.  There usually aren't many such messages.
INFO: Log the detailed steps running inside my software.  For example, when an interface method is called, a SYSTEM log message is written as mentioned above, and the entire calling routine into the internal modules within the interface method will be recorded with INFO messages.  The idea behind is these messages could help us identify the detailed call stack for trouble-shooting or debugging. This is the source of the use-up-disk-space issue: There are always SO MANY INFO messages when the software is running normally.

My tries and thoughts
1). I tried to not record any INFO log messages.  This resolves the disk space issue but I also lose a lot of information for debugging.  Think about this: My customer is in a different city and it's expensive to go there often.  Besides, they use an intranet that is 100% inaccessible from outside.  Therefore: we can't always send engineers on-site as soon as they meet problems; we can't start a remote debug session.  Thus log files, I think, are the only way we could make use to figure out the root of the trouble.
2). Maybe I could make the logging strategy configurable at run-time(currently it's before the software runs), that is: At normal run-time, the software only records SYSTEM and ERROR logs; when a problem arises, somebody could change the logging configuration so the INFO messages could be logged.  But still: Who could change the configuration at run-time?  Maybe we should educate the software admin?
3). Maybe I could always turn the INFO message logging on but pack the log files into a compressed package periodically?  Hmm...
Finally...
What is your experience in your projects/work?  Any thoughts/ideas/comments are welcome!
EDIT
THANKS for all your effort!!! Here is a summary of the key points from all the replies below(and I'll give them a try):
1). Do not use large log files.  Use relatively small ones.
2). Deal with the oldest ones periodically(Either delete them or zip and put them to a larger storage).
3). Implement run-time configurable logging strategy.
Comment: for log-rotation, see http://linux.about.com/od/commands/l/blcmdl8_logrota.htm
Answer: Your (3) is standard practice in the world of UNIX system logging.

When log file reaches a certain age or maximum size, start a new one
Zip or otherwise compress the old one
throw away the nth oldest compressed log
Answer: There are two important things to take note of:

Extremely large files are unwieldy. They are hard to transmit, hard to investigate, ...
Log files are mostly text, and text is compressible

In my experience, a simple way to deal with this is:

Only write small files: start a new file for a new session or when the current file grows past a preset limit (I have found 50 MB to be quite effective). To help locate the file in which the logs have been written, make the date and time of creation part of the file name.
Compress the logs, either offline (once the file is finished) or online (on the fly).
Put up a cleaning routine in place, delete all files older than X days or whenever you reach more than 10, 20 or 50 files, delete the oldest.

If you wish to keep the System and Error logs longer, you might duplicate them in a specific rotating file that only track them.
Put altogether, this gives the following log folder:
 Log/
   info.120229.081643.log.gz // <-- older file (to be purged soon)
   info.120306.080423.log // <-- complete (50 MB) file started at log in
                                 (to be compressed soon)
   info.120306.131743.log // <-- current file

   mon.120102.080417.log.gz // <-- older mon file
   mon.120229.081643.log.gz // <-- older mon file
   mon.120306.080423.log // <-- current mon file (System + Error only)

Depending on whether you can schedule (cron) the cleanup task, you may simply spin up a thread for cleanup within your application. Whether you go with a purge date or a number of files limit is a choice you have to make, either is effective.
Note: from experience, a 50MB ends up weighing around 10MB when compressed on the fly and less than 5MB when compressed offline (on the fly is less efficient).
Answer: One way to deal with it is to rotate log files.
Start logging into a new file once you reach certain size and keep last couple of log files before you start overwriting the first one.
You will not have all possible info but you will have at least some stuff leading up to the issue.
The logging strategy sounds unusual but you have your reasons.
Answer: I would
a) Make the level of detail in the log messages configurable at run time.
b) Create a new log file for each day. You can then get cron to either compress them and/or delete them or perhaps transfer to off-ling storage.
Answer: My answer is to write long logs and then tweat out the info you want.
Compress them on a daily basis - but keep them for a week
Answer: I like to log a lot. In some programs I've kept the last n lines in memory and written to disk in case of an error or the user requesting support.
In one program it would keep the last 400 lines in memory and save this to a logging database upon an error. A separate service monitored this database and sent a HTTP request containing summary information to a service at our office which added this to a database there.
We had a program on each of our desktop machines that showed a list (updated by F5) of issues, which we could assign to ourselves and mark as processed. But now I'm getting carried away :)
This worked very well to help us support many users at several customers. If an error occurred on a PDA somewhere running our software then within a minute or so we'd get a new item on our screens. We'd often phone a user before they realised they had a problem.
We had a filtering mechanism to automatically process or assign issues that we knew we'd fixed or didn't care much about.
In other programs I've had hourly or daily files which are deleted after n days either by the program itself or by a dedicated log cleaning service.


Cannot access div which is created by ajax (is dynamic)

Question: I'm developing an app using Electron and I want to make different pages. I created an index.html, and another one: seeds.html. (I will be adding more and this one is just for test)
What I do is to load the content of the selected page (ex. addseed.html) via jQuery .load() inside a div with "main" class in index.html.
Now the problem is after I load addseed, the table doesn't show older queries. I tested and it can read the file correctly, but the main problem is appending them to the dynamically created table. However, after I add a new item, it shows correctly, but older items don't.
(there are "contact"s instead of "seed"s cause I'm going through a tutorial and code is just for test :D )
function addEntry(seed, price, image) {
    if(seed && price && image) {
        sno++
        let updateString = '
 ' + sno + '	 '+ seed +'	 ' + price +'
'
        $('#contact-table').append(updateString)
    }
}
function loadAndDisplayContacts() {
   $("#status").text("function works\n")
   //Check if file exists
   if(fs.existsSync('contacts.txt')) {
       let data = fs.readFileSync('contacts.txt', 'utf8').split('\n')

       data.forEach((contact, index) => {
           let [ seed, price, image ] = contact.split(',')
          addEntry(seed, price, image)
       })
   } else {
       console.log("File Doesn\'t Exist. Creating new file.")
       fs.writeFile('contacts.txt', '', (err) => {
           if(err)
               console.log(err)
       })
   }
}

$(document).on('click', '#addseed', () => {
    $(".main").load("addseed.html")
    loadAndDisplayContacts()
})

and this the html for 'addseed.html':

    Seed
    <input type="text" Seed="Seed" value="" id="Seed" placeholder="Seed" class="form-control" required>

    Price
    <input type="Price" Seed="Price" value="" id="Price"
       placeholder="Price" class="form-control" required>

    Image
    <input type="Image" Seed="Image" value="" id="Image"
       placeholder="Image" class="form-control" required>

<button id="openFile" onclick="openFile();">Open</button>

this is filepath:

    <button class="btn btn-primary" id="add">Add to list!</button>

            S. No.
            Seed
            Price
            Image

and in index.html I have:
    <button id="addseed">Add</button>

Answer: You're not waiting for the asynchronous AJAX to complete. You need to call the function that depends on the updated DOM as a callback function.
$(document).on('click', '#addseed', () => {
    $(".main").load("addseed.html", loadAndDisplayContacts)
})

And in addseed.html, change class="container main" to just class="container". You're loading the file into the main DIV in index.html, it doesn't replace the DIV. So you're creating two DIVs with that class, and the next click loads the file into both of them.
Comment: I've updated the answer to explain what you need to do.
Comment: Thanks for your answer, but there's another problem: when I change the page and come back, the whole table is duplicated.
Comment: You have `class="main"` in `index.html`, and also in `addseed.html`. The next time you click, it loads the content into both of them, so you get a duplicate.
Comment: So should I remove (empty) the table each time or it is better to prevent adding duplicate rows?


Inheritance and service class

Question: It's, I think somethin basic in OOP :
Environment : C#/.net 2.0
Let's say I have two class :
public class Animal
{

}
public class Dog : Animal
{

}

A service class with two method :
 public void DoStuff(Animal animal)
    {
        Console.Write("Animal stuff");
    }
    public void DoStuff(Dog animal)
    {
        Console.Write("Dog stuff");
    }

If I execute the following code :
 Animal instance = new Animal();
        MyService.DoStuff(instance);

        Animal instance2 = new Dog();
        MyService.DoStuff(instance2);

"Animal stuff" is printed twice.
So my question is : why ? And how can I get "Animal stuff" and "Dog stuff" without casting instance2, or moving the method from my service to my class (in fact I would like that my code works, but it's not :()
Thanks
PS : These are just example :)

Because the Visitor pattern is not really appealing, I'll just move my service's method to my class, waiting for a better solution.
Answer: You aren't overriding the doStuff() method in Dog, because the parameter type is different.  They're two separate methods.
Either change the signature in Dog to match Animal or create a Visitor that sorts it out for you.
Here's one way to write it:
public interface Animal {  void accept(AnimalVisitor visitor); }

public class AbstractAnimal : Animal
{
    public void accept(AnimalVisitor visitor) { visitor.visit(this); }
}

public class Dog : AbstractAnimal {}

public class Cat : AbstractAnimal {}

public interface AnimalVisitor
{
    void visit(Animal animal);
    void visit(Dog dog);
    void visit(Cat cat);
}

Now the service (and all others) can implement AnimalVisitor and do different things to each Animal subtype.
It's a common pattern called "double dispatch"; you can read more about it in Scott Meyers' "More Effective C++".
Comment: doStuff is not a part of Dog or animal class, can you explain about the visitor ?
Comment: I just read more about this pattern and indeed it seems like a solution, but it has some default : 1/ it needs a lot of code to be implemented, 2/ we lost the benefit of the service class : we had a way to its method in the animal class, 3/ if you don't know this pattern you don't know what's going on !
Comment: I think I know the pattern; you're the one that doesn't know what's going on.  1. "A lot of code" - I don't know where you got that idea.  There's some code, to be sure, but not a lot.  2. Your Animal and Dog classes have no methods in them at all when I write this.  I can't tell about "a way to the service method in the Animal class", because there is no implementation.  3. I don't know the pattern?  You had to look it up.  I'd say you're the one that doesn't know what's going on.
Comment: @remi, I couldn't see anything about the Dog or Animal class, since both are empty.  And the Visitor moves the doStuff out of the classes being visited, so it satisfies that requirement.
Comment: ": AbstractAnimal" , it's the way I'm talking about. How do I do if there is more parameters in the "accept" method ? And I never said that you don't know the pattern, why would I said that, I'm just speaking about me and my colleagues.
Comment: I think there is a mistake in your implementation : you need to add a call to visit() in the Dog class (so you have to make accept virtual and then create an override), if you don't then you'll always use "void visit(Animal animal);" instead of "void visit(Dog dog);
" when you have a Dog . Can you confirm ?
Answer: The reason is that the second call, although passing a Dog, is passing a reference to an animal. That reference can be any type of animal (you just happen to have passed a Dog) but .NET does not know that so it must call the version of the method that accepts a reference to an Animal rather than the more specific reference.
Comment: Ok, but why this would work if doStuff were a part of the animal and the dog class ? Still .net would reference an Animal but it will call the Dog's method.
Comment: I presume you mean that you would have a virtual method on Animal that was overriden in the Dog class? Then you have an inheritance relationship between the methods and the compiler can help out you. You have not defined (and cannot define) such a relationship in your service class
Comment: My remark was just a question about the logic behind all this : If I override a class method, .net will call the right one, but if I override a service class method .net won't that's why I'm kind of surprised.
Comment: But you are not overriding in the service class. That's the difference, you are just creating a new method with a very similar signature on the same class. Overriding uses inheritance to get do what it does. Your service class is not inheriting any behaviour to override.
Answer: Another thing which might seem a hack is to cast the passed parameter to dynamic. This would let you implement a 'dynamic visitor', so that for example you would write
foreach (dynamic a in animals)
  doStuff(a);

void doStuff(Cat c) { ... }
void doStuff(Dog d) { ... }

and so on. This lets you avoid the 'double dispatch' approach completely because you're using dynamic dispatch instead. Please be aware that this approach is much more computationally intensive and might be infeasible in some (e.g., iterative) scenarios.

Inheritance and service class


How to set a default handler for "CSRF verification failed" in django?

Question: According to the Django documentation, we can set the a default error handler like this:
handler403 = 'mysite.views.my_custom_permission_denied_view'
...

My handler for 404 and 500 is working fine. But in case of access forbidden, I can't trigger it (when I raise HttpResponseForbidden, the triggered handler is the handler for error 500). Anyway, that's not my problem. My problem is when I try to tamper (for testing purposes) the CSRF token, it throws "Forbidden" but again, my handler for access forbidden is not invoked - it invokes the default django template for 403 forbidden. And when I try to access the root directory of static (or media) directory, the invoked page is from the servers default forbidden page (apache httpd in my case) which is fine.
My question is:

How to set default handler for "CSRF verification failed"?
What are the cases that the 403 handler is being called?
How can I trigger a 403 forbidden error?

Here is my setup:

Python 3.4
Django 1.10 (production, debug = False)
Server: Apache httpd through mod_wsgi
Windows 7 32bit
Answer: You can do, in settings
CSRF_FAILURE_VIEW = 'your_app_name.views.csrf_failure'

in view
def csrf_failure(request, reason=""):
    ctx = {'message': 'some custom messages'}
    return render(request, your_custom_template, ctx)

Comment: Works great. Thanks.
Answer: I think you should read this:
https://docs.djangoproject.com/en/1.10/ref/settings/#std:setting-CSRF_FAILURE_VIEW
(found it in the link you provided)
It looks that CSRF is handled little differently in django - and it is not standard handler403;


PageMethod vs ajax async call

Question: I am new asp.net and want to call server side method from java script.
For that I can do this using ajax call and PageMethod.
Now my question is which one is better to use?
<code>$.ajax({})
</code>
Or
<code>PageMethods.FunctionName(Parameter);
</code>
Comment: Juhi this is not a site to get suggestions instead you have to post some code which you tried to do but you stuck there. Although you can go for the ajax.
Comment: I wanted to know which is better/efficient for my web application
Comment: No doubt ajax is the way to go.
Answer: if you have already put Ajax scrip manager. you can user any method.
but if you have not put script manager i suggest you should go for Ajax asynchronous call
Page methods are much more openly accessible.and it is not good idea to put script manager just for web method calling
Answer: No one can tell better than Dave Ward
https://web.archive.org/web/20161229045603/http://encosia.com/using-jquery-to-directly-call-aspnet-ajax-page-methods/
Page methods are much more openly accessible. The relative unimportance of EnablePageMethods is a nice surprise.
<code>$.ajax({
  type: "POST",
  url: "PageName.aspx/MethodName",
  data: "{}",
  contentType: "application/json; charset=utf-8",
  dataType: "json",
  success: function(msg) {
    // Do something interesting here.
  }
});
</code>

PageMethod vs ajax async call


Getting session variable in view contextual filter drupal 8

Question: I am new to Drupal 8. I get group_id in session variable just like that <code>$_SESSION['groupbysession']['group_id'] = $path[2];</code>. now i want to get that session variable in view Contextual filters.I have no idea how to do this. I also use view extra module for this but doesn't work for me.Thanks in advance
Comment: `now i want to get that session variable in view Contextual filters` you mean you want to pass that session variable value as a contextual filter value?
Comment: Yes i want to pass that session variable value as a contextual filter value. Thanks for your reply
Comment: `I also use view extra module for this but doesn't work for me.` it would seem more pertinent to report "what doesn't work" to that module issue queue so they can fix a bug if in fact that is what is occurring.
Answer: You'll need to create a custom module and pass the value Group ID value using hook_views_pre_view
Example:
<code>/*
 * Implements hook_views_pre_view()
 */
function mymodule_views_pre_view(ViewExecutable $view, $display_id, array &$args) {
  // Modify contextual filters for my_special_view.
  if ($view->id() == 'my_special_view') { // target a specific view
    // if you want you could make it even more specific by adding ex: "&& $display_id == 'block_1')"
    $group_id = $_SESSION['groupbysession']['group_id'];
    $args[0] = $group_id; // set argument
  }
}
</code>
Comment: @Kevin Thanks a lot for your response. I try it now.


Highcharts: Attach a click event to dataLabel when useHTML set to true

Question: I have a networkGraph in Highcharts and there's a click event attached to the "points", however I'd like to fire that event when an item within the dataLabel is clicked.
This fiddle is similar to what I have https://jsfiddle.net/BlackLabel/xsLnmd0u/, which Wojciech has been very helpful with. Notice that if you click the dataLabel nothing happens. But if you set useHTML to false then clicking the dataLabel does the same as clicking the marker.
In my version I have some spans inside the dataLabel that I want to fire the click event with, but it doesn't work at the moment.
Answer: You can add events to nodes dataLabels using js addEventListener like that:
  chart: {
    type: 'networkgraph',
    marginTop: 50,
    events: {
      load: function() {
        var nodes = this.series[0].nodes;

        nodes.forEach(function(node) {
          node.dataLabel.div.addEventListener('click', function(e) {
            console.log('click')
          });
        });
      }
    }
  }

Demo:

https://jsfiddle.net/BlackLabel/8uy4aq6z/


What am I doing wrong in this algebra excercise?

Question: This is my first question here, so please forgive me if the format etc. are not quite right. I've been attacking an algebra question, and my workings are below. There's a mistake somewhere (I don't know where) because my workings don't reach the correct answer! I'd really appreciate someone letting me know where I'm slipping up:
I have two functions, $G$ as a function of $N$ and $N$ as a function of $l:$
$G(N) = \frac{N}{40}\cdot  100$
$N(l) = \frac{300}{l} + 5$
I need to compose a function that represents $G$ as a function of $l.$ I do it like this:
$$G(l) = \frac{\frac{300}{l}+5}{40}\cdot 100 = \frac{\frac{100 \cdot 300}{l} + 100 \cdot 5}{40}=\frac{\frac{30,000}{l} + 500}{40}= \frac{750}{l} + 12.5$$
And that's it. ...but it's wrong.
Thanks so much for your help with this!
Comment: Why do you say that the answer is wrong? What result did you expect?
Comment: See http://meta.math.stackexchange.com/questions/5020/mathjax-basic-tutorial-and-quick-reference for formatting.
Comment: The arithmetic adds up...  Is there an answer key somewhere?
Comment: Correct as far as eye can see.
Answer: You did nothing wrong. The calculation is correct.
Maybe it is easier to see with
$$
G(N) = \frac{5}{2} N
= \frac{5}{2} \cdot 300 \cdot \frac{1}{l} + \frac{5}{2} \cdot 5
= 750 \frac{1}{l} + 12.5
$$
Comment: Apparently that actually was right. Sorry everyone. Thanks for your help, and for latexing my question. I'll learn how to use that. How can I mark my question as "done"?


2D Heat Transfer Laplacian with Neumann, Robin, and Dirichlet Conditions on a semi-infinite slab

Question: So, I know I'm missing something simple, but I can't find a way to solve the Laplacian with the boundary conditions I've got down.
The Problem:
"Consider the semi-infinite plate sketched below with thickness 2b. The temperature at the base (x = 0) is constant at $T_0$. Heat is transferred on both sides of the plate to a surrounding temperature $T_{\infty}$. The conductivity of the plate is k and the heat transfer coefficient for both sides is h. There is no heat generation. As $x \rightarrow \infty $, the temperature is finite. Solve for steady state temperature."
Below is a sketch of the problem

So far I've managed to define my PDE
$$\frac {\partial^2T}{\partial y^2} + \frac {\partial^2T}{\partial x^2} = 0$$
and boundary conditions
\begin{align}
T(0,y) &= T_0 \\
T(\infty , y) &< \infty \\
\frac{\partial T}{\partial y}(x,b) &= - \frac hk [T_b(x) - T_{\infty}] \\
&= f(x) \\
\frac{\partial T}{\partial y}(x,0) &= 0
\end{align}
And I know I'm going to use my separation of variables, but I run into trouble when I try to solve my boundary conditions. I can't re-figure my boundary conditions in a way that gives me a known eigenvalue (generally of the form $\lambda = \frac{n\pi}b$) without giving me some $\sin(\infty)$ kind of a condition. I've tried for a few hours to find boundary conditions that work, but at this point I'm thinking I've either forgotten a simple trick, or I never learned how to deal with Laplacian boundary conditions approaching infinity. Any help would be appreciated.
Also, this is my first post and I'm sure I've left out some important detail or committed some faux pas. Please let me know if I've committed any breaches of etiquette, or if there's something I've left out.
Answer: This is because you are considering the equation on the half-line. Your domain is essentially $\Omega=[0,\infty)\times [0,y]$
If you look at the heat equation and wave equation on a bounded domain, you will see the solutions are typically given as Fourier Series, but on unbounded domains, the solutions look a lot different. You cannot use boundary methods and separation of variables to solve the PDE here.
Generally speaking, we want solutions $u(x,y)$ which "vanish at infinity" (tend towards $0$ as $||u(x,y)||_{L^2}\rightarrow \infty)$. Functions which are smooth and have compact support (denoted by $C_{c}^{\infty}(\Omega)$) include those that vanish at infinity $C_{0}(\Omega)$. These conditions imposed on the solutions are desirable because they make physical sense. The temperature/potential in a rod is not going to shoot off to infinity, it's going to decrease with time until it reaches a steady-state.
Now to actually solve the PDE, I don't think there is a slick and easy way to do it. Solutions to Laplace's equation in domains which aren't on a disk $D^n$ tend to be ad-hoc and very specific to the domain. Polynomials wouldn't work because they do not vanish at infinity. I would try to look for solutions which use sines and cosines. Alternatively, you could look for a harmonic function on the domain $[0,\infty)\times [0,y]$ (you don't necessarily need to work in the complex plane for this). Start by looking for qualitative solutions and then try to get a concrete, quantitative one.
Comment: Could you clarify what you mean by "look for solutions"? Do you mean guessing a solution like $T(x,y) = \sum A_n sin(\lambda y) e^{- \lambda x}$ and applying boundary conditions?

As an aside, the professor who wrote this added a note that this problem should be solvable by separation of variables, but he's known for accidentally writing problems that aren't solvable or don't give real answers.
Comment: Yes, something of that flavor would probably work. The professor likely made a mistake, boundary conditions do not work when your domain is unbounded, otherwise, the heat kernel, D'Alembert's solution, etc. all would be pointless, and they do not coincide with the Fourier series solution. There is a reason we have solutions for different domains. However, the condition that the solution is finite as $lim_{x \rightarrow \infty}$ is finite is exactly a condition commonly imposed on all solutions to PDEs on unbounded domains. You don't want the solution to "blow-up".
Comment: It is likely the PDE is written in bad form, $\infty$ is clearly not a defined value, so it makes no sense to think of it is a boundary in the normal sense, but imposing a condition at infinity where the solution either vanishes, or at least is finite (no blow-up), is valid and common practice. Separation of Variables may work here, but you in general have to be very careful as this is not a "true" boundary.


How to Join 2 tables using lambda expression

Question: Can anyone show me how to write this sql query using lambda expression.
I am trying to join CoachingLang.ExpandedForm & CoachingLang.ExpandedCategory to CoachingDef.FormCategory.
SELECT Ef.Translation +' - '+ Ec.Translation, Fc.FormCategoryID, Ef.FormId,Ef.Translation, Ec.CategoryId, Ec.Translation
FROM CoachingDef.FormCategory Fc
INNER JOIN CoachingLang.ExpandedForm Ef ON Fc.FormID = Ef.FormId
AND Ef.DictionaryId = -2147483645 AND Ef.PropertyId = -2147483647
INNER JOIN CoachingLang.ExpandedCategory Ec ON Fc.CategoryID = Ec.CategoryId
AND Ec.DictionaryId = -2147483645 AND Ec.PropertyId = -2147483647

Answer: from Fc in CoachingDef.FormCategory
join Ef in CoachingLang.ExpandedForm on Fc.FormID equals Ef.FormId
join Ec in CoachingLang.ExpandedCategory on Fc.CategoryID equals Ec.CategoryId
where Ef.DictionaryId = -2147483645 && Ef.PropertyId = -2147483647
&& Ec.DictionaryId = -2147483645 && Ec.PropertyId = -2147483647

select new {Translation = Ef.Translation +' - '+ Ec.Translation,
    Fc.FormCategoryID, Ef.FormId,Ef.Translation,
    Ec.CategoryId, Ec.Translation}

Answer: Joins are messy in Lambda form, but here goes:
 CoachingDef.FormCategory
            .Join(CoachingLang.ExpandedForm,
                  Fc => new {Fc.FormID,
                             DictionaryId = -2147483645,
                             PropertyId = -2147483647}  // primary key
                  Ef => new {Ef.FormId,
                             Ef.DictionaryId,
                             Ef.PropertyId}   // foreign key
                  (Fc,Ef) => new {Fc, Ef})
            .Join(CoachingLang.ExpandedCategory,   // the "left" side is now the merged Fc/Ef type
                  FcEf => new {FeEf.Fc.CategoryID,
                               DictionaryId = -2147483645,
                               PropertyId = -2147483647}  // primary key
                  Ec => new {Ec.CategoryId,
                             Ec.DictionaryId,
                             Ec.PropertyId}   // foreign key
                  (FcEf,Ec) => new {FcEf.Fc, FcEf.Ef, Ec})
             .Select(FcEfEc => new {Translation = FcEfEc.Ef.Translation +' - '+ FcEfEc.Ec.Translation,
                                    FcEfEc.Fc.FormCategoryID,
                                    FcEfEc.Ef.FormId,
                                    FcEfEc.Ef.Translation,
                                    Ec.CategoryId,
                                    Ec.Translation
                                   })

It's a little cleaner in query syntax:
from Fc in CoachingDef.FormCategory
join Ef in CoachingLang.ExpandedForm on
    new {Fc.FormID,
         DictionaryId = -2147483645,
         PropertyId = -2147483647}
    equals new { Ef.FormId,
         Ef.DictionaryId,
         Ef.PropertyId}
join Ec in CoachingLang.ExpandedCategory on
    new {Fc.CategoryID,
         DictionaryId = -2147483645,
         PropertyId = -2147483647}
    equals new Ec.CategoryId,
         Ec.DictionaryId,
         Ec.PropertyId}
select new {Translation = Ef.Translation +' - '+ Ec.Translation,
            Fc.FormCategoryID,
            Ef.FormId,
            Ef.Translation,
            Ec.CategoryId,
            Ec.Translation}


Is there an installation package builder for Drupal?

Question: Does anybody know of any websites that provide a service that allows you to select which modules you want, and download a pre-assembled installation package with the selected modules already in the /modules/ folder?
Answer: You could make your own easily with the Drush Make module; the Profiler Builder module will tell you what to include in your make file.
This requires you have some knowledge of using drush.
Comment: See also: http://drupal.org/node/1368242, which contains a drush command to generate profiles (still under development)
Comment: Ok, thanks guys. That's what I thought. I wonder if there is a call for a website that provides a kind of package building service, such as on the jQuery UI site?
Comment: This kind of site already exists : http://drushmake.me/


Definition of codimension of variety

Question: Let $X$ be a variety over field $k$.
A Weil divisor on $X$ is an integral linear combination of irreducible subvarieties of $X$ of codimension $1$.
So I want to know the definition of codimension of a subvariety.
Let $Y$ be a subvariety of $X$ , where subvariety means a closed subscheme of an open subscheme of $X$ to be a variety.
What is the definition of codimension of $Y$ in $X$ $??$
Answer: Just assume $Y$ is irreducible here.
Let's do the affine case first. If  $S = \text{Spec}(A)$ is an irreducible affine variety (with $A$ a finitely-generated $k$-algebra) and $Z = V(\mathfrak p)$ is an irreducible closed subvariety with $\mathfrak p\subset A$ a prime ideal, then the codimension of $Z$ in $S$ is $\dim A - \dim A/\mathfrak p = \text{ht}(\mathfrak p)$. (This equality is a fact of integral $k$-algebras and other catenary rings.) In other words, it is the length $\ell$ of the longest chain of irreducible closed subvarieties $Z\subsetneq Z_1 \subsetneq \dots \subsetneq Z_\ell = S$.
Now suppose $Y$ is an irreducible closed subvariety of the open irreducible affine subvariety $U$ of $X$. Let $V\subset U$ be an open affine which intersects $Y$. Now $Y_V = Y\cap V$ is a closed irreducible subvariety of the irreducible affine variety $V$. The codimension of $Y$ in $X$ is the codimension of $Y_V$ in $V$. You can check that this is independent of the various choices.

Definition of codimension of variety


Change line width in ggplot, not size

Question: I see several posts about changing line width in ggplot. The answers, while informative and effective for the OP, change the line size. That is, ggplot seems to treat lines as a series of units, and size increases both the length and width of each unit, making other adjustments coarser.
I'm hoping there is a way to make lines wider (thicker) without also affecting length and, in turn, the scale of dashes.
I borrowed some code from https://cran.r-project.org/web/packages/ggplot2/vignettes/ggplot2-specs.html to illustrate what I mean:
library(ggplot2)

#A simple plot with manually set dashes.
#The first numeral is units of dash length, the second units in the gap in hexadecimal.
lty <- c("11", "18", "1f", "81", "88", "8f", "f1", "f8", "ff")
linetypes <- data.frame(y = seq_along(lty), lty = lty)

ggplot(linetypes, aes(0, y)) +
  geom_segment(aes(xend = 5, yend = y, linetype = lty)) +
  scale_linetype_identity() +
  geom_text(aes(label = lty), hjust = 0, nudge_y = 0.2) +
  scale_x_continuous(NULL, breaks = NULL) +
  scale_y_reverse(NULL, breaks = NULL)

#Altering the size changes the line width AND dash spacing.

ggplot(linetypes, aes(0, y)) +
  geom_segment(aes(xend = 5, yend = y, linetype = lty),
     size = 3) +
  scale_linetype_identity() +
  geom_text(aes(label = lty), hjust = 0, nudge_y = 0.3) +
  scale_x_continuous(NULL, breaks = NULL) +
  scale_y_reverse(NULL, breaks = NULL)

Essentially what I want is thick lines with relatively thin and finely adjusted gaps. I think this is the same question asked another way: Is there a way to make lines that are all, say, "dashed" vary in width but not in the relative location of the dashes? Like this (which I totally faked):
Comment: I just want to mention that a similar question was posted here: https://stackoverflow.com/questions/63061601/how-to-keep-linetype-spacing-constant-despite-line-size/. Some of the answers may be a solution for your problem too.
Answer: From the ?par helpfile for "Line Type Specification" (bold added for emphasis):

Line types can either be specified by giving an index into a small
  built-in table of line types (1 = solid, 2 = dashed, etc, see lty
  above) or directly as the lengths of on/off stretches of line.
  This is done with a string of an even number (up to eight) of
  characters, namely non-zero (hexadecimal) digits which give the
  lengths in consecutive positions in the string. For example, the
  string "33" specifies three units on followed by three off and
  "3313" specifies three units on followed by three off followed by
  one on and finally three off. The 'units' here are (on most devices)
  proportional to lwd, and with lwd = 1 are in pixels or points or
  1/96 inch.

This suggests that if we specify linetypes and line widths that vary appropriately (e.g. the thicker line is twice as wide as the thinner line, with on-off stretches half as long), we can achieve the desired effect of seemingly identical dash lengths at different line widths.
Note: the allowed characters in the linetype specification are c(1:9, "A":"F")), which means the shortest possible stretch length is 1 unit, while the longest is 15 units. This limits the number of different lines that can be created.
It works as expected with the base R plotting functions:
plot.new()
plot.window(xlim=c(0, 5), ylim=c(1, 3))
abline(h = 3, lty = "22", lwd = 8)
abline(h = 2, lty = "44", lwd = 4)
abline(h = 1, lty = "88", lwd = 2)
axis(2, at = 3:1, labels=c("22", "44", "88"), tick = FALSE, las = 1)

For ggplot2, on the other hand, as far as I've been able to ascertain, the choice of graphics file device matters. The dashes align neatly for vector-based devices, but not necessarily for bitmap-based ones:
p <- ggplot(data.frame(y = seq(1, 3),
                       lty = c("11", "22", "44"),
                       lwd = c(8, 4, 2)),
            aes(0, y)) +
  geom_segment(aes(xend = 5, yend = y,
                   linetype = lty,
                   lwd = lwd)) +
  geom_text(aes(label = lty), hjust = 0, nudge_x = -0.3) +

  scale_linetype_identity() +
  scale_size_identity() +
  scale_x_continuous(NULL, breaks = NULL) +
  scale_y_reverse(NULL, breaks = NULL, expand = c(0.5, 0))

# bitmap devices
ggsave("test.bmp", p + ggtitle(".bmp"))
ggsave("test.jpg", p + ggtitle(".jpg"))
ggsave("test.png", p + ggtitle(".png"))
ggsave("test.tiff", p + ggtitle(".tiff"))
ggsave("test.wmf", p + ggtitle(".wmf"))

# vector devices
ggsave("test.eps", p + ggtitle(".eps"))
ggsave("test.pdf", p + ggtitle(".pdf"))
ggsave("test.svg", p + ggtitle(".svg"))

I haven't found anything that addresses this directly within ggplot2. Still, if you need one of the bitmap formats but identically spaced dashes are a top priority, you can output your plots to one of the vector-based devices first, and convert from one file format to another thereafter.
Comment: Thanks for the useful info!

But it also suggests to me that there is no solution to my problem. Customizing lty with hexadecimal numbers, and ignoring dot-dashes, you can have 15^2 = 225 dash/space combinations. Sounds great! But if you widen the line, it quickly becomes an awkward balancing act between making the line clearly visible and keeping lty numbers low enough that it doesn't end up looking like the lower half of my second figure, i.e. bad.

I'm just learning ggplot, so I do appreciate the insight!

Change line width in ggplot, not size


Django model - how to model history and current

Question: I want to model Employee, and his contracts. So for example there is Employee1, and can have 3 contracts:
from 01-2021 to 05-2021,
from 05-2021 to 08-2023,
from 08-2023 to 10-2024,
Obviously the last one is current. We can model it with 2 models, and simple FK relationship.
But - in most cases I will not need historical data, but just a current contract. To get it - some manipulation is needed ie.  joining employee with contracts, and filtering based on current date.
I prefer to avoid it, and have (in Employee model?)  some field called "current contract" ??
But then some logic will be needed to update it... when any update/create on Contracts is done.
Is there any inteligent way to handle such cases?
Comment: can employees have two concurrent contracts?
Comment: lets assume not.
Comment: then "current contract" idea seems reasonable to me. Imho, selecting on a employee+date  index isn't that expensive, but if you want to avoid that some logic outside the DB is inevitable
Answer: You can have the Employee model and Contract being a Foreign key to Employee.
For example
from django.utils impprt timezone

class Employee(models.Model):
    first_name = models.CharField(max_length=50)
    # ... other fields

    def get_current_contract(self):
        return self.contract_set.all() \
               # the filter can be optional or customised depending on your use case
               .filter(start_date__lte=timezone.now()) \
               .order_by("-start_date") \
               .first()

class Contract(models.Model):
    employee = models.ForeignKey('Employee', on_delete=models.CASCADE)
    start_date= models.DateField(default=timezone.now)
    description = models.TextField()

   class Meta:
       unique_together = ["start_date", "employee"]

Something like the above will suffice. There is a restriction to avoid having a contract starting on the same date for the same employee and a method to get the latest contract. That way you can keep a record and also get the latest contract.
You can also add an is_present field but that would require always setting every other contract but the current one as False. Hope you understand the logic here.


Python - Reordering the final list in a list of lists and having all corresponding list indices change to the same index ordering

Question: I have a list of lists in python i.e.
[[6.0, 3.0, 16.0, 3.0], [3.0, 2.0, 5.0, 7.0], [4.0, 3.0, 2.0, 1.0]]
I then want to order the final list in the list of lists by ascending numerical size, but the change of order in the indexes of this list I want to be applied to the other corresponding indexes in the other lists within the list. For example,
[[6.0, 3.0, 16.0, 3.0], [3.0, 2.0, 5.0, 7.0], [4.0, 3.0, 2.0, 1.0]]
turns into
[[3.0, 16.0, 3.0, 6.0], [7.0, 5.0, 2.0, 3.0], [1.0, 2.0, 3.0, 4.0]]

Apologies if this isn't worded greatly, I am rather new to python.
I have looked into using the zip and sorted functions however haven't been able to use them to the effect I want to.
Answer: One way to do this is to associate to each number in the list you are ordering to an incrementing index - and then use this incrementing index as target for each element in the previous lists.
def order_by_last(data):
     indexes = list(enumerate(data[-1]))
     indexes.sort(key=lambda pair: pair[1])
     new_list = [[sublist[index[0]] for index in indexes]   for sublist in data]
     return new_list

In [56]: order_by_last([[6.0, 3.0, 16.0, 3.0], [3.0, 2.0, 5.0, 7.0], [4.0, 3.0, 2.0, 1.0]])
Out[56]: [[3.0, 16.0, 3.0, 6.0], [7.0, 5.0, 2.0, 3.0], [1.0, 2.0, 3.0, 4.0]]

Answer: I'm not sure if you are willing to use external libraries, but you need an argsort for this one from numpy argsort. Note that the output is not a python list, but rather a numpy array (which can be converted though).
So you can get your result by doing the following:
# done list_of_lists
list_order = argsort(list_of_lists[-1])
new_list = []
for single_list in list_of_lists:
     buffer_list = []
     for position in list_order:
         buffer_list.append(single_list[position])
     new_list.append(buffer_list)

Keep in mind though that if your lists are different sizes, this might break.
Answer: >>> a = [[6.0, 3.0, 16.0, 3.0], [3.0, 2.0, 5.0, 7.0], [4.0, 3.0, 2.0, 1.0]]

>>> list(zip(*sorted((zip(*a)), key=lambda x: x[-1])))
[(3.0, 16.0, 3.0, 6.0), (7.0, 5.0, 2.0, 3.0), (1.0, 2.0, 3.0, 4.0)]

I'm using two idioms here:

zip(*list_of_lists) acts as a matrix transposer by swapping rows and columns of the matrix, represented by a list of lists.
sorting the transposed list of lists by the value of the last element.
Comment: [A code-only answer is not high quality](//meta.stackoverflow.com/questions/392712/explaining-entirely-code-based-answers). While this code may be useful, you can improve it by saying why it works, how it works, when it should be used, and what its limitations are. Please [edit] your answer to include explanation and link to relevant documentation.
Answer: Create a sorted list of indexes based on the last list, then recreate each other list based on these indexes.
l = [[6.0, 3.0, 16.0, 3.0], [3.0, 2.0, 5.0, 7.0], [4.0, 3.0, 2.0, 1.0]]
indexes = sorted(range(len(l[-1])), key=lambda x:l[-1][x])
res = [[x[i] for i in indexes] for x in l]

Answer: One option is to use zip to restructure the list into columnwise tuples, sort them and then turn that back into original lists:
L = [[6.0, 3.0, 16.0, 3.0], [3.0, 2.0, 5.0, 7.0], [4.0, 3.0, 2.0, 1.0]]

R = [*map(list,zip(*sorted(zip(*L[::-1]))))][::-1]

# [[3.0, 16.0, 3.0, 6.0], [7.0, 5.0, 2.0, 3.0], [1.0, 2.0, 3.0, 4.0]]

Another way (much less efficient but perhaps more readable) is to sort each row based on the last row's corresponding values:
R = [ [v for _,v in sorted(zip(L[-1],r))] for r in L ]


How to make editable menus with OpenCms

Question: How to make editable menus with OpenCms. I want when user clicks on edit button then he can change anything with menu - menu label, Link URL, he can add/del an item from sub-menu list etc.
Answer: You can put a <cms:editable/> tag in your JSP, so when the user un logged in, he will see the OpenCMS editable icon (blue, white and red circle). You must put the cms editable tag anywhere at the beginning of the page. Then, you mark your content tag (<cms:include>, <cms:content>, etc.) as editable, with editable atribute.
Example:
<%@ taglib prefix="cms" uri="http://www.opencms.org/taglib/cms" %>

(things here...)

<cms:editable/>

(more things here...)

<cms:contentload collector="allInFolderDateReleasedDesc" param="<%=url%>" editable="true">
(content html...)
</cms:contentload>

<cms:contentload collector="allInFolderDateReleasedDesc" param="<%=url2%>" editable="false">
(content html...)
</cms:contentload>

With this, you have one "direct editable" element, and other not editable.
Hope it helps.
P.S.: More references in http://www.vinu.edu/cms/opencms/alkacon-documentation/documentation_taglib/docu_tag_editable.html
Comment: Can u guide me what is url we have to provide, because i am not able to provide correct url value
Answer: You should use a structured content definition (xsd) to define your page sections and it's elements, i.e. in your case it would be an embedded menu.xsd for example with label, link, etc.
In the jsp template for it, you would use  and then page will be editable, lead the user to the editor to edit the structured content.
Not sure if this short answer helps, but I don't know the status of your development and how far it's already done, if you're using structured content or not, etc.
The OpenCms docs
http://www.bng-galiza.org/opencms/opencms/alkacon-documentation/documentation_xmlcontent/
would be a good reference and starting point; although I must admit the learning curve for OpenCms is not low due to lack of beginner's tutorials/documentation.
Answer: I know this question is already answered but...
The best way doing customizable menus with OpenCms is to use the Navigation property of every item. With relatively simple programming you can build your menu scanning all "navigable" items in a folder. Users can just edit Navigation title and position of the menu option keeping multi-language feature.
Take a look here:
http://www.opencms-wiki.org/wiki/Example_template_with_tree_menu

How to make editable menus with OpenCms


Trouble installing ghc-mod

Question: I'm trying to install GHC-MOD on Windows 10 x64 on GHC 8.0.1 with cabal:
C:\WINDOWS\system32>cabal install ghc-mod
Resolving dependencies...
cabal: Could not resolve dependencies:
trying: ghc-mod-184.108.40.206 (user goal)
trying: djinn-lib-0.0.1.2/installed-I8G... (dependency of djinn-ghc-0.0.2.3)
next goal: mtl (dependency of ghc-mod-220.127.116.11)
rejecting: mtl-2.2.1/installed-6qs... (conflict: mtl =>
transformers==0.5.2.0/installed-0.5..., ghc-mod => transformers<0.5)
rejecting: mtl-2.2.1, mtl-126.96.36.199, mtl-2.2, mtl-22.214.171.124, mtl-2.1.2, mtl-2.1.1,
mtl-2.1, mtl-188.8.131.52, mtl-188.8.131.52, mtl-126.96.36.199, mtl-18.104.22.168, mtl-126.96.36.199,
mtl-184.108.40.206, mtl-220.127.116.11, mtl-126.96.36.199, mtl-1.0 (conflict: djinn-lib =>
mtl==2.2.1/installed-6qs...)
Backjump limit reached (currently 2000, change with --max-backjumps or try to
run with --reorder-goals).

Then changing backjumps:
C:\WINDOWS\system32>cabal install ghc-mod --max-backjumps 9999
Resolving dependencies...
Configuring old-time-220.127.116.11...
Failed to install old-time-126.96.36.199
Build log ( C:\Users\xx\AppData\Roaming\cabal\logs\old-time-188.8.131.52.log ):
Configuring old-time-188.8.131.52...
configure: WARNING: unrecognized options: --with-compiler
checking for gcc... C:\PROGRA~1\HASKEL~1\802E01~1.1\mingw\bin\gcc.exe
checking whether the C compiler works... no
configure: error: in `/cygdrive/c/Users/xx/AppData/Local/Temp/cabal-tmp-3644/old-time-220.127.116.11':
configure: error: C compiler cannot create executables
See `config.log' for more details
cabal: Leaving directory 'C:\Users\xx\AppData\Local\Temp\cabal-tmp-3644\old-time-18.104.22.168'
cabal: Error: some packages failed to install:
cpphs-1.20.1 depends on old-time-18.104.22.168 which failed to install.
ghc-mod-5.0.0 depends on old-time-18.104.22.168 which failed to install.
haskell-src-exts-1.17.1 depends on old-time-126.96.36.199 which failed to install.
hlint-1.9.32 depends on old-time-220.127.116.11 which failed to install.
old-time-188.8.131.52 failed during the configure step. The exception was:
ExitFailure 77

I've tried installing both MinGW+MSYS and Cygwin, but neither works. All the GHC folders are in the PATH environment variable.
Comment: I installed stack, but it forced me to downgrade from GHC 8.0.1 to 7.10, I'm not sure stack works with GHC 8
Comment: last time I checked you needed to use the ghc-8 branch to get ghc-mod working with ghc8 anyway - so `install ghc-mod` probably will not work with 8.0.1 right now
Comment: Try `stack`, it just works.
Answer: https://github.com/DanielG/ghc-mod/issues/798
Officially, ghc-mod is not updated to GHC 8. There's a branch ghc-8 for it where some tests are still broken but other things supposedly work.
The ghc-8 branch seems to work for me. It builds and I can use it. I use Stack on Linux.

Trouble installing ghc-mod


Are the square brackets in Clojure's defn, defmacro and binding really a vector?

Question: Are the square brackets around arguments in Clojure's defn, defmacro and binding (am I forgetting some?) really creating a vector or is it just a matter of syntax, making the arguments stand out from the rest?
I'm reading Clojure in Action which states:

Clojure uses vectors to denote
  function arguments or binding forms.

which made me ask this question here.
Answer: Yes, it is really a vector.  We can see that by building a function manually and then evaluating it:
(eval (list (list 'fn (vector 'x) (list '* 'x 2)) 100))
;=> 200

Hope that helps.
Comment: The `defn` form is a macro so at the time it's examined (macroexpansion time) nothing has been evaluated. So when it looks at the binding form it expects a vector but instead sees a list `(vector (quote x) (quote y))`.
Comment: One question though (after two and a half years...), why isn't this accepted? (defn foo (vector 'x 'y) (+ x y))
Comment: Ah, I have been macro'd again. Tnx.


How to extract Facebook page likes and profile picture from Facebook API output

Question: I'm using Nokogiri 1.7.1 and Rails 4.2.4 in my application. When I view Facebook's source code, there is no HTML or CSS allowing me to select and scrape the text.
Facebook is using React code:
// ....
showSponsorTaggerButtonNUX:false,showSponsorTaggerDirectBoost:false,showSponsorTaggerSponsorRelationship:false}},attachmentsConfig:{STATUS:{canScrapeShare:true,canAttachLocation:false,enabled:true,largeTextThreshold:85,profileID:null,profileName:null,profileURI:null,profilePicSrc:"https://scontent.fsvg1-1.fna.fbcdn.net/v/t1.0-1/c184.108.40.206/p40x40/10354686_10150004552801856_220367501106153455_n.jpg?oh=3ad0945d50cb5c25455167972e2cb9c6&oe=5A0CA7F8"
// ....

For instance I found profilePicSrc. I tried using at_css and xpath. I might doing it wrong or it can't scrape them because there is no CSS or HTML that Nokogiri can select/find.
I managed to get these details from the Facebook API:
{
   "id": "7270241753",
   "name": "YouTube",
   "cover": {
      "cover_id": "10156001238986754",
      "offset_x": 0,
      "offset_y": 0,
      "source": "https://scontent.xx.fbcdn.net/v/t1.0-9/s720x720/14591676_10156001238986754_7091829954587846661_n.jpg?oh=b5bc4ca11e6a5d47f18b798eb38cc176&oe=59DBEC50",
      "id": "10156001238986754"
   },
   "fan_count": 82634405,
   "picture": {
      "data": {
         "is_silhouette": false,
         "url": "https://scontent.xx.fbcdn.net/v/t1.0-1/p50x50/19424472_10156001229851754_375700039380897185_n.jpg?oh=965b50ea998545bcbcb99fb90b3ba606&oe=59CEF703"
      }
   }
}

How can I select the profile picture, name, the number of likes the page has and its big header image from this output?
Comment: You are not allowed to scrape Facebook to extract data in the first place. If you want to interact with pages on Facebook - then use their API.
Comment: thanks @CBroe, I have never used Facebook API before. What would the API link be for getting a page's details?
Comment: https://developers.facebook.com/docs/graph-api/reference/page/
Comment: Thanks a bunch @CBroe could you please take a look at the question once more. I have updated with some outputs.
Comment: That's JSON, and once you decode it, you got a nested data structure. How to access that in ruby/RoR, I don't know - but that should be easy enough to research, and is not Facebook-specific.
Comment: Welcome to Stack Overflow. Please read "[ask]" and "[mcve]". Your question isn't asked well. What did you try? Why didn't it work? Nokogiri doesn't process JavaScript so it will not help you.
Answer: As nokogiri doesn't process javascript, I end up using Facebook open graph to get page data in json format and did a JSON.load(open(link)) and parsed them from the output.


Upper Bound Theorem for Simplicial Spheres

Question: I am recently approaching combinatorial commutative algebra and I am studing Upper Bound Theorem for Simplicial Spheres (Stanley 1975).
My question is so a bit general and maybe ingenuous...
Momentum curve is the algebraic curve $M \subset \mathbb{R}^d$ defined parametrically by
$x(\tau) = (\tau, \tau^2, ..., \tau^d) $.
A cyclic polytope $C(n, d)$ is the convex hull of any $n$ distinct points on $M$.
There is a first Proposition I have seen,that says any cyclic polytope is a symplicial $d$- polytope (since you can prove any $d+1$ dinstinct points on $M$ are affinely independent).
Question 1) Are there other algebraic curves with this property?
More over you can prove the combinatorial type of a cyclic polytope $C(n, d)$ depends only upon $n$ and $d$ and not on the particular vertex set $V \subset M$.
Question 2) Are there other algebraic curves with this property?
So the point is: I do not understand the peculiarity of momentum curve.
Maybe there is another curve $N$ such that if you take the convex hull of $n$ distinct points, call it $N(n, d)$, you can reformulate upper bound theorem for simplicial spheres in this way:
Given $P$ a simplicial complex whose geometric realization is topologically a sphere, with n vertices, the following inequality holds: $f_j(P) \le f_j(N(n, d))$, where $f_j$ is any component of the $f$-vector.
If such a curve does not exist, why?
I think McMullen's formulated the conjecture, so how did he find the momentum curve?
Thanks
Comment: This particular curve is simply very convenient to describe and (sort of) visualize. What really matters is the combinatorial type of the cyclic polytope.
Comment: The answer to Question 1 is *Yes*, but probably in an unsatisfactory way: $(\tau, 2\tau^2,3\tau^3,...,d\tau ^d)$ does the trick, and you can find other trivial modifications. Question 2 sounds interesting, but I expect the answer to be no.
Answer: To your last (unnumbered) questions:
Suppose that such a function $N(n,d)$ exists with $f_i(P)\le f_i(N(n,d))$ for all simplicial spheres $P$.
This must in particular hold for the boundary complex of the cyclic polytope.
Therefore
$$f_i(C(n,d))\le f_i(N(n,d)).$$
But by the upper bound theorem for simplicial spheres (proven by Richard Stanley), we also have
$$f_i(N(n,d))\le f_i(C(n,d))$$
as well, establishing identity, and so $N(n,d)$ must be cyclic.


Redirect the TCP traffic to stdin of CLI application?

Question: I have a console application, listening the stdin for the input data and printing the output to stdout. Is it possible to redirect the TCP traffic from the remote client to stdin of the launched application? Is it possible with Windows 7 toolchain?
Answer: You could use netcat for Windows to listen for tcp connections and pipe the data stream to stdin and/or stdout.


Schumann posthumous variation V's choice on descending the semitone or whole tone

Question: Here is the starting part of Schumann posthumous variation V,

I am interested in knowing the "logic" or the "reasoning" why and how Schumann chose the descending tones of the following middle melody (marked in blue and green):

What the middle melody shows in the blue color has:
flat B -> A -> flat A -> flat G -> flat G -> F -> E -> F, (Melody 1)
which descends by

semitone, semitone, whole tone, stay same tone, semitone, semitone, ascend semitone back to F. (1)

What the middle melody shows in the green color has:
F -> flat E -> flat E -> flat D -> flat D -> C -> B -> C, (Melody 2)
which descends by

whole tone, stay same tone, whole tone, stay same tone, semitone, semitone, ascend semitone back to F. (2)

My question is, for the purpose of making a more symmetric and perhaps also mystic sound, why not Schumann chose in the middle melody shows in the green color as:
F -> E -> flat E -> flat D -> flat D -> C -> B -> C, (Melody 3)
which descends by

semitone, semitone, whole tone, stay same tone, semitone, semitone, ascend semitone back to F. (3)

In comparison, the choice of melody (1) and (3) seems more natural, more natural (in my opinion) than the choice of Schumann's choice on the melody (1) and (2). Could we give a good reasoning/explanation behind?
Comment: Another question regarding the same piece: [On Schumann posthumous variation V's note on a natural G or a flat G](https://music.stackexchange.com/q/115856/70803).
Comment: Thanks so much for reminding us-  I have many questions about this piece indeed... It is very puzzling how he composed this. I even feel that he heard certain "voices" when he composed this music (those four lines of melodies in the first four bars just come from his imagination or his own way of grasping those "voices".)
Answer: TL;DR

Measures 1–4 comprise two, 2-bar segments.

Within each 2-bar segment, the final melodic note of each harmony is repeated as the first note of the following harmony. Thus, the Eb (third note of bar 4) must be preceded by an Eb (second note of bar 4).
For every harmony, the melody contains at least one chord tone. Thus, since the first note of bar 4 (F) is not a chord tone, the second note must be (as the chord changes with the third melody note).

Both the above and below explanations are summarized in the below graphic.
Legend

Harmonic groupings are indicated by color.
Chord tones within a harmonic grouping have full-size note heads.
Repeated notes across harmonic boundaries are indicated by dotted slurs.

Reframe the question
The question boils down to why, on measure 4's second melodic note, did Schumann write an Eb rather than an Fb?
Built into this question is the tacit assumption that the important element is the interval between the first and second pitches in each measure. (Measure three begins with a half step. Why doesn't measure four?) However, the problem is best answered by reframing the question as why did Schumann not immediately precede measure 4's third melodic note with a note a step above?
Melodic breakdown
Beginning in measure 1, consider each sequence of four melodic pitches, with particular attention to the second and third of each group (in bold).

measure/beats
pitches
beat 2–3 interval

m. 1, b. 1–2
Bb — Ab — Gb — F
Descending whole step

m. 1, b. 3–4
Eb — Db — C — Cb
Descending half step

m. 2, b. 1–2
Cb — Bb — A — Bb
Descending half step

m. 2, b. 3–4
Bb — Ab — G — Ab
Descending half step

m. 3, b. 1–2
Bb — Bbb — Ab — Gb
Descending half step

m. 3, b. 3–4
Gb — F — E — F
Descending half step

m. 4, b. 1–2
F — Eb — Eb - Db
Unison

m. 4, b. 3–4
Db — C — B — C
Descending half step

It's clear that in all but one case, there is a descending step from the second to third pitch. However, this reveals the presence of two intervallic outliers: the measure 4 unison already in question, but also the measure 1 descending whole step. So now the question becomes why are two intervallic relationships different from all the others?
Harmonic breakdown
Next, consider the harmonic structure of the first four measures:

measure/beats
chord
RNA

m. 1, b. 1–4
Db
I

m. 2, b. 1–2
Gb
IV

m. 2, b. 3–4
Db
I

m. 3, b. 1–2
Ab7
V7

m. 3, b. 3–4
Bb-7
ii7/V

m. 4, b. 1
Ab
C[6-4]/V

m. 4, b. 2
Eb7
V7/V

m. 4, b. 3–4
Ab7
V7

Notice the harmonic rhythm: 4 beats, 2 beats, 2 beats || 2 beats, 1 beat, 1 beat, 2 beats. The pipes denote the division of the two, 2-bar segments comprising the four bars being considered.
All harmonies last two beats except the first measure and the first two beats of the fourth measure — corresponding exactly to the two intervallic outliers. Nearly the entire first measure is devoted to a descending scale (Db major/Bb minor) over a single harmony (Db major), and the melodic notes stick to that scale; thus, the descending whole step. However, nearly every time there is a chord change, Schumann ends the first chord and begins the second with a unison melody note.
The "nearly" points up another seeming anomaly: why do the chord transitions all involve unison melody notes except from measure 2 into measure 3?
This is due to the internal structure of the phrase, shown above. Measure 2 is the end of one motivic segment, and Measure 3 is the beginning of a new motivic segment. This is evidenced, in fact, by the ascending step between the two measures, which returns the music in m. 3 to the same pitch(-class) as started the first measure (Bb).
Another reason
For every harmony, its accompanying melodic segment contains at least one chord tone. Since measure 4's beat 1 and beat 2 comprise different harmonies, either the first or second notes of beat 1's melody must be a chord tone. Since the first note is F — a non-chord tone — the second must be. Thus, the second note can't be Fb — a non-chord tone.
Comment: Thank you Aaron so much for this - it will take me a little more time to digest the full answer. And yes, you understand my issue 100% - thanks!!!
Comment: May I know which software that you typed music? Is that Finale or something? Thanks!
Comment: @wonderich I used MuseScore.