problem getting hook_menu() to work

Question: I want to display a button on the front page of my website and for the first time (as beginner), I wanted the link to be configured in the administration page. I followed the tutorial on creating a module configuration and the code I wrote doesn't seem to show a textfield while visiting admin/config/content/linkpresent.
/**
 * fonction permettant de gérer le lien de la bannière du front
 */
function mij_page_presentation() {
  return 'hello world';
}

/**
 * function in admin pages
 */
function mij_page_admin() {
  $form = array ();
  $form ['mij_page_presentation'] = array (
      '#type'   => 'textfield',
      '#title'  => t('Lien renvoyant vers la page de présentation '),
      '#size' => '255',
      '#default_value'  => '',
      '#description' => t('Ici est renseigné le lien renvoyant vers la page de présentation '),
      '#required' =>TRUE,
  );
  return system_settings_form($form);
}

/**
 * implements hook_menu
 */
function mij_page_menu(){
  $items = array();

  $items['admin/config/content/linkpresent']=array(
      'title' => 'Lien de la page de présentation',
      'description'=>'Ici est renseigné le lien renvoyant vers la page de présentation ',
      'page callback'=> 'drupal_get_form',
      'access arguments' => array('administer mij_page settings'),
      'type' => MENU_NORMAL_ITEM,
  );
  return $items;
}

function mij_page_admin_validate($form, &$form_state){
  $presentation = $form_state['values']['mij_page_presentation'];
  if(is_numeric($presentation)){
    form_set_error('mij_page_presentation',t('veuillez entrer une URL relative valide'));
  }
}

Here is the blank page I obtain in the administration page.

Anyone has an idea on this?
Answer: Your page arguments are missing, so Drupal doesn't know what form to load.
Change your hook_menu implementation to this:
function mij_page_menu(){
  $items = array();

  $items['admin/config/content/linkpresent']=array(
      'title' => 'Lien de la page de présentation',
      'description'=>'Ici est renseigné le lien renvoyant vers la page de présentation ',
      'page callback'=> 'drupal_get_form',
      'page arguments' => array('mij_page_admin'),
      'access arguments' => array('administer mij_page settings'),
      'type' => MENU_NORMAL_ITEM,
  );
  return $items;
}

Remember to clear Drupal's caches after you make the change.
Comment: Because you're using a system settings form the data will be stored automatically - you can get it anywhere in code with `variable_get('mij_page_presentation', 'default_value');`
Comment: Perfect ! It is working. I can't validate your answer for now (have to wait 3 more minutes).
I have one more question : How can i keep the data I enter in the textfield and how to get it in my code to use it elsewhere ?

problem getting hook_menu() to work


.htaccess code to redirect HTTP requests to HTTPS

Question: I recently migrated my website from HTTP to HTTPS. I read on various websites about redirecting all HTTP requests to HTTPS using .htaccess codes.
Lots of websites provide different codes and now I'm confused which code should I use.
Following are 4 codes found on various websites:
1st code:
RewriteEngine on
RewriteCond %{HTTP_HOST} ^yoursite.com [NC,OR]
RewriteCond %{HTTP_HOST} ^www.yoursite.com [NC]
RewriteRule ^(.*)$ https://www.yoursite.com/$1 [L,R=301,NC]

2nd code:
RewriteEngine On
RewriteCond %{HTTPS} !=on
RewriteRule ^/?(.*) https://%{SERVER_NAME}/$1 [R,L]

3rd code:
RewriteCond %{SERVER_PORT} 80
RewriteRule ^(.*)$ https://www.example.com/$1 [R,L]

4th code:
NameVirtualHost *:80
<VirtualHost *:80>
ServerName www.example.com
Redirect permanent / https://secure.example.com/
</VirtualHost>

<VirtualHost _default_:443>
ServerName secure.example.com
DocumentRoot /usr/local/apache2/htdocs
SSLEngine On
</VirtualHost>

Please guide me which code is perfect and I should put in my .htaccess file?
Comment: It depends on your own environment, since each of these examples have their own assumptions on the environment they are running in.
Comment: Option #1 is invalid (possibly taken out of context?). From your other questions, it seems you have access to the server config, so this isn't something you should be doing in `.htaccess` anyway, as HBruijn suggests below.
Answer: For starters: the last configuration snippet is not even valid in .htaccess files...
(But since you shouldn't be using .htaccess files anyway if you're a system administrator that's not an issue.)
Redirecting http to https a text book example of when (as an admin) you should not need a mod_rewrite approach and use a simple redirect instead. So, if you do have access to the main server config, your last snippet with a simple redirect from the plain http VirtualHost is recommended.
Comment: Please don't blindly follow recipes without understanding what to do: http://blog.lastinfirstout.net/2009/11/cargo-cult-system-administration.html - as Tero already commented, it depends a bit on what else is configured.
Comment: I have access to the main server config and I'm using 3rd code in `pre_virtualhost_global.conf` file. When I checked the apache.org link shared by you, it doesn't contain `NameVirtualHost *:80` line at the beginning and there are some more changes between 4th code shared by me and the code given at apache.org. Can you please tell me which code is correct?
Comment: We cannot tell which one to use since we don't know about your configuration.


Speaker clipping when bass guitar controls turned up, but not when amplifier controls turned up to same volume

Question: I've noticed if I have my bass guitar's volume and bass EQ knobs turned all the way up, it sounds like the speaker is clipping. If I then turn the volume and bass down on the guitar while turning the volume and bass on the amplifier up to the same volume, I get no speaker clipping/distortion.
Would the problem be in the pickups, or the knobs? It's a cheap bass with active electronics, so I could see either one being the culprit.
My short-term fix has been to leave the controls dialed down a little on the guitar, but I'd like to know I'm not gonna kill my speakers if I accidentally turn a knob a too far.
Answer: The pickups could be clipping the input gain stage of your amplifier.  I doubt it has anything to do with the knobs, since active electronics can give out a very hot signal.  Can you give us more information on what you're using for an amplifier?  What active electronics are you using, specifically?
I doubt you'll kill the speakers if it is input clipping since it's hitting that the hardest, first.
However, what you'll probably have to do is plug into the padded input (usually marked something like  hi or -10) which will pad the hot pickups down to a more reasonable volume; if you have such an input on your bass amplifier.  Otherwise, you could use an EQ pedal and manually adjust the level so that the entire signal is dropped a bit before hitting the amplifier.
A more long-term solution would be upgrading your amp to an amp that allows input gain adjustment, and possibly even higher-efficiency speakers that may tolerate the hot signal better.
Comment: The amp is a Kustom KB200H and I've got it going into a backline 410-blx. I'm plugging into the padded input (-6db), but even when I turn the amp gain down and the guitar up I get more clipping than if I turn the amp gain up and the guitar down.As far as what kind of active electronics I'm not positive. It's just a cheap Johnson Bass so I'm sure they're nothing fancy. Would upgrading the pick-ups smooth the output out at higher volumes?
Comment: Could be pickups then. Also try other answer, maybe a finnicky battery too.
Comment: I did turn the gain almost all the way down and the other amp controls up which cleaned up the sound nicely, I guess I was mostly fiddling with the volume and EQ controls before. Thank you sir, I'll probably look at some new pick-ups, as the Johnson's output still feels more 'jagged' than my active Ibanez's on the same equipment.
Comment: Could be, EMG makes some nice pickups that are active if you'd like to stick with those.  However, there are plenty of beautiful sounding passive pickups out there to check out too.  Depending on who you choose, they may be less expensive than EMGs.
Comment: If your speaker cabinet includes tweeters (high-frequency drivers), these can be damaged by clipping even at power levels far below the rated maximum for the cabinet - a clipped signal contains a much higher proportion of high frequencies meaning much more power than usual will be going into the tweeter.
Answer: If you're using active electronics, as silly as this sounds, verify that the battery isn't dead.  I had a similar issue with my first bass, and it turned out to be the 5 dollar 9-volt battery-swap fix.  After verifying that, as stated in the previous answer, see if you can pad the input somehow to make sure that you're not slamming the preamp.
Comment: Replaced the battery just for grins, no improvement. Went with the gain adjustment suggested in Shawn's answer
Answer: Sounds like you are overloading the pre amp.Just as a guitarist would when turning up the pre-gain.To clean up that sound, he would turn the volume down at the guitar.At that point, the guitar volume pot. becomes a sort of distortion control. What's wrong with leaving the bass guitar volume down enough to achieve a clean sound, and turning up the amp?   On my active basses, dead battery = no sound at all.
Comment: I guess it just irks me on some level, not having the full range of control at the guitar. Also I use several basses, so once I've found a happy medium between them in the amp controls, I try to leave it alone as much as possible. The Johnson for some reason just comes in hotter than the rest.
Comment: Can you clear up a point ? Does this phenomenon occur on only the  Johnson bass, or all of them?
Comment: Only the Johnson, the other basses have a smoother feel to the output at their highest volumes. It's that last centimeter of a turn on the Johnson's volume that kills it. I'm not sure if the volume pot controls the pre-amp's gain or just dampens the signal coming out of the pre-amp, but it feels to me like too much gain or just a crummy signal to begin with. So that kinda narrows it down to pick-ups vs. pre-amp I guess.
Comment: The vol. pot on guitars and basses cut down the signal to the pre-amp.Sounds like the bass is at fault, if the same thing doesn't happen with other basses.


Saving a copy of incoming mail for specific recipient in Exim

Question: I need to archive important mail incoming for specific address in case it gets accidentally deleted from email server, etc.
Either saving or using a pipe to archive it on backup machine is fine (I can rsync the backup automatically later, etc).
However, I have trouble to get system_filter working. I have configured it this way so far:
/etc/exim4/exim4.conf:
system_filter = /etc/exim4/system_filter
system_filter_user = Debian-exim
system_filter_group = Debian-exim

system_filter_directory_transport = local_copy_to_directory

# transport section

local_copy_to_directory:
    driver = appendfile
    delivery_date_add
    envelope_to_add
    return_path_add
    group = Debian-exim
    user = Debian-exim
    mode = 0660
    maildir_format = true
    create_directory = true

In /etc/exim4/system_filter:
# Exim filter
if $local_part is "example"
then
    unseen save /tmp/example_dir
endif

Nothing gets written in logs, nothing gets saved (normal delivery occurs of course).
When I change $local_part in system filter file to root and test it like so:
% exim  -bF /etc/exim4/system_filter -d-all+filter -f email@example.com  <tfpmet
Exim version 4.89 uid=0 gid=0 pid=1261 D=200
...
Return-path taken from "Return-path:" header line
Return-path = firstname.lastname@example.com
Sender      = email@example.com
Recipient   = firstname.lastname@example.com
Testing Exim filter file "/etc/exim4/system_filter"

Condition is true: $local_part is root
Unseen save message to: /tmp/example_dir
Filtering did not set up a significant delivery.
Normal delivery will occur.
  >>>>>>>>>>>>>>>> Exim pid=1261 terminating with rc=0 >>>>>>>>>>>>>>>>

It clearly says:
Condition is true: $local_part is root
Unseen save message to: /tmp/example_dir

However, nothing gets saved again.
OS: Debian 9.11 amd64.
I'd prefer to achieve this result using system filter, but any good solution would do really.
Answer: It might not be the most elegant of solutions, but 'procmail' can do that. In the .procmail file for that user you create a copy:
:0 c
/var/mail/backup_file


ReLU gradient descent matrix dimensionality

Question: If I'm backpropagating through a recurrent neural network, say my layer output is $$h_t  = \text{ReLU}(U h_{t-1} + V x_t),$$ when calculating the gradient my dimensions don't seem to be coming out properly. I'm looking to take the gradient of h with respect to $h_{t-1}$ which I'm assuming is
$$ \frac{\partial h_t}{\partial h_{t-1}} = \frac{\partial \text{ReLU}(A)}{\partial A}\frac{\partial A}{\partial h_{t-1}}$$ where $$\frac{\partial A}{\partial h_{t-1}} = \frac{\partial (U h_{t-1} + Vx_t)}{\partial h_{t-1}} = \frac{\partial (U h_{t-1})}{\partial h_{t-1}} = U^T$$ (in denominator notation).
If $h \in \mathbb{R}^n$ I would expect $\partial h_t/\partial h_{t-1}$ to have dimensions $[n \times n]$, however I believe $\frac{\partial \text{ReLU}(A)}{\partial A}$ has dimensions $[n \times 1]$ and I know U^T has dimensions $[n \times n]$, so those two obviously can't be multiplied in any way to get a final dimension $[n \times n]$. Any suggestions?
Answer: The derivative of the ReLu in terms of $A$ is actually $n\times n$. This is because $A$ has n dimensions, and so does the output. I think maybe you thought that $A$ is a scaler, but in fact it's a scaler in each of its components. Also don't forget that the derivative of the ReLu in component $ij$ is 0 whenever $A_j<0$.
Answer: The derivative of the ReLu function is the Heaviside step function
$$
\frac{dr(a)}{da} = s(a) =\begin{cases}
1  &\text{if } a \ge 0 \\
0 &\text{otherwise}
\end{cases}
$$ Note that I've used $s(a)$ for the step function instead of the more standard $H(x)$ because the symbols $(h,x)$ have other meanings in this problem. I also want to use the convention where uppercase Latin letters represent matrices, lowercase Latin are vectors, and Greek letters are scalars.
When applied element-wise to a vector argument, the differential of the ReLu function can be written using the element-wise (aka Hadamard $\circ$) product as
$$dr=s\circ da$$
For this problem, we have
$$\eqalign{
a &= Uh+Vx_+ \cr
s &= s(a) \cr
h_+ &= r(a) \cr
}$$
Now find the differential and then the gradient of the function
$$\eqalign{
dh_+ &= s\circ da = s\circ(U\,dh) \cr
  &= \Big({\rm Diag}(s)\,U\Big)\,dh \cr
\frac{\partial h_+}{\partial h} &= {\rm Diag}(s)\,U \cr
}$$


How to sort "weekday, day" format using dataTable and jQuery with internationalization?

Question: I have a web app that uses globalize.js for globalization. I'm trying to sort a column that uses the following format: "Tuesday, 22" (en-US) or "Terça-Feira, 22" (pt-BR).
I used this block of code to test:
jQuery.extend(jQuery.fn.dataTableExt.oSort, {
    "weekdays-sort-pre": function (a) {
        return a.replace(/^.+,/, "");
    },

    "weekdays-sort-desc": function (a, b) {
        return ((a  b) ? 1 : 0));
    },

    "weekdays-sort-desc": function (a, b) {
        return ((a  b) ? -1 : 0));
    }
});

But it didn't sort correctly. Actually, the result i got you can see here:
Screen example
Does anyone know how to ignore the first part (day of week) and use only the numbers to sort?
The result I want:
Sunday, 24
Friday, 29
Saturday, 30

Answer: The sorting plugin has two major problems :

It has two desc implementations
It does not return the number as actual number

Here is an improved version
jQuery.extend(jQuery.fn.dataTableExt.oSort, {
    "weekdays-sort-pre": function (a) {
        return parseInt(a.replace(/^.+,/, ""))   //return number
    },
    "weekdays-sort-desc": function (a, b) {
        return ((a  b) ? 1 : 0));
    },
    "weekdays-sort-asc": function (a, b) {       //implement asc
        return ((a  b) ? -1 : 0));
    }
});

And you must of course actually use the plugin (not totally clear from the question) :
var table = $('#example').DataTable({
   columnDefs: [
     { targets: [0], type: 'weekdays-sort'}
   ]
})

demo -> http://jsfiddle.net/kjjsdumc/
The internationalisation-part is redundant since all you need is to extract a number from a string.
Comment: Thank you so much. In addition to what you gave to me, I had to update the plugin. I got it now.


Geometric Generalized Linear Model

Question: I'm practicing for a Statistical Models test I have tomorrow, most of it is going well but I'm having issues with the Generalized Linear Model portion of the course. Here is the situation. We have $n$ independent observations which we assume to be geometric, the parameter $\pi_i$ depends on three covariates, let's call them $A$, $B$, and $C$. This gives us the following:
$Z_i \sim Geom(\pi_i)$
$P(Z_i=k)=\pi_i(1-\pi_i)^k$
$\eta_i=x_{iA}\beta_1+x_{iB}\beta_2+x_{iC}\beta_3=g(\pi_i)$
I need to show that this density function is part of the exponential family with the following properties:
$f(y,\theta_i)=exp\{\frac{y\theta_i-b(\theta_i)}{\phi/A_i}+c(y,\phi/A_i)\}$
I start by transforming $P(Z_i=k)$:
$P(Z_i=k)=\pi_i(1-\pi_i)^k=exp\{ln(\pi_i(1-\pi_i)^k)\}=e^{ln(\pi_i)+k\cdot ln(1-\pi_i)}$
Since $\pi_i \in (0,1)$ we need $g(\pi_i)$ to map from $(0,1)\rightarrow\mathbb{R}$ which in turn means $g^{-1}(\theta_i)$ maps from $\mathbb{R}\rightarrow(0,1)$
An option would be to use the logit link function, correct? Since we are trying to estimate probabilities. That would mean we get:
$\theta_i=g(\pi_i)=ln(\frac{\pi_i}{1-\pi_i})$
From this follows: $\pi_i=\frac{e^{\theta_i}}{1+e^{\theta_i}}=\frac{1}{1+e^{-\theta_i}}$
If I plug either into the transformed density function I keep ending up with a term $k\cdot ln(1+e^{\theta_i})$ while the $f(y,\theta_i)$ should have $k\cdot \theta_i$ or $k\cdot ln({e^{\theta_i}})$
I feel like I'm doing something wrong, all the literature suggests this link function but I cannot get it to fit to the exponential family. Suggestions?
Answer: Your derivations are correct up to the point when you try to insist on using the logit function as the canonical link. Don't impose a functional form on $\theta_i$, let the distribution guide you. How should $\theta_i$ be defined so that $k\theta_i$ shows up in the exponent? You already figured out that $\theta_i=\ln(\pi_i/(1-\pi_i))$ won't work.
Note
While this answers your direct question, I just realized that you will have further difficulties while trying to link in covariates. The reason is that your  parametrization is not particularly useful for modeling, since $p$ is not the expected value. You might want to reparametrize your model with the distribution mean before linking it to covariates.
Comment: So that would be $\theta_i=ln(1-\pi_i)$ then? $\pi_i=1-e^{e^{\theta_i}}$ would give that result. But doesn't that give a problem in the $e^{ln(\pi_i)}$ part? Or since you can cancel these that doesn't matter? Thanks for your help
Comment: Yes, that's the right choice, though I think you messed up the solution for $\pi_i$. The rest of the terms don't have $k$, so they will wind up in the other undefined functions.

Geometric Generalized Linear Model


How to make Slider similar/gallery to the Amazon product Slider

Question: I building a website, and I am not good in js or jQuery. I have no idea what to do. I was in search for couple days, to find any library that support this feature. However, there are different libraries I found, but most of them are separate from what I need, zoom and thumbnails. It has to be similar to Amazon or eBay product listing slider.
Can any one give me a clue where should I start?
PS. I tried swiper.js, but it has zoom only on double click.
Updated 5/16/2017
Example
Comment: Seems like any major slider would do that if you configure it to be like ebay/amazon. Have you looked at flexslider?
Comment: @MichaelCoker yes, but would not help because I dont have good experience in the js
Comment: Which slider you referring in amazon main slider or products slider?
Comment: @RajKumarBhardwaj product slider
Comment: http://prntscr.com/f8bsfn   this one?  can you show me your website link?
Comment: @RajKumarBhardwaj no, not this one. Probably. I was wrong. The main one that has thumbnail and zoom. When you going to the product. You will see slider on the left side.
Answer: Hi first of all visit to the link http://www.landmarkmlp.com/js-plugin/owl.carousel/ and download slider.
open your header of the website theme and put the js and CSS which one mentions into the snippet below, and replace the images, js and css files path which where it is.
After that put the HTML sections where you would like to show your slider, and replace the div with your dynamic products loop code.

 $(document).ready(function($) {
      $("#owl-example").owlCarousel();
    });

    $("body").data("page", "frontpage");
<link href="http://www.landmarkmlp.com/js-plugin/owl.carousel/assets/css/custom.css" rel="stylesheet">

    <link href="http://www.landmarkmlp.com/js-plugin/owl.carousel/owl-carousel/owl.carousel.css" rel="stylesheet">
    <link href="http://www.landmarkmlp.com/js-plugin/owl.carousel/owl-carousel/owl.theme.css" rel="stylesheet">

Touch

Can touch this

Grab

Can grab this

Responsive

Fully responsive!

CSS3

3D Acceleration.

Multiply

Owls on page.

Modern

Browsers Compatibility

Zombie

Browsers Compatibility

Take Control

The way you like

Light

As a feather

Tons

of options

Hope so it will work for you. You just need to update files path according where it is situated in your website files directories.
Comment: This not what I meant, I was saying the slider that has gallery in it.


Python/Gspread : code to remove whitespace and format data

Question: I am building a little tool to scrape a TTRPG website for data and write the data into a google sheet.  This is my code thus far :
import requests
from bs4 import BeautifulSoup
import gspread

gc = gspread.service_account(filename='credentials.json')

sh = gc.open('D&D_Tables').sheet1

url = 'https://www.d20srd.org/srd/monsters/achaierai.htm'
r = requests.get(url)
soup = BeautifulSoup(r.text, 'html.parser')
# line below uses Beautiful Soup to locate table entries within HTML, returns all results as text
monster_stats_table = soup.find('table', class_='statBlock').text
# line below converts to dictionary, other program returns an error
new_mst =[monster_stats_table]
sh.append_row(new_mst) # currently appends all information to one cell, needs to be broken up

The information shows up in one cell, stretched out over dozens of rows, with a lot of extra whitespace.  I have tried several methods to remove the whitespace and format the data correctly, but nothing seems to be working out.  Showing Problem
  I am trying to have the table look something like this instead:   Correct Table  Thank you for any help or suggestions you can provide. :)
I have attempted to use .strip method, as well as both importing json library and (separately) importing ast library to use funtions suggested to remove the whitespace.  Neither could return output as a result of the formatting of the raw data.  I am thinking I need to find a way to write the data to a json object and then find a way to import that into the sheet, but I am not certain that is the best way, or how to do that.
Answer: I don't use GSpread but here's something that should make your work with structured data easier, for example, you can easily import this to a GSpread sheet.
import pandas as pd
import requests

url = "https://www.d20srd.org/srd/monsters/achaierai.htm"
df = pd.read_html(requests.get(url).content.decode("utf-8"), flavor="bs4")
pd.concat(df).to_csv("achaierai.csv", index=False, header=False)

This outputs a .csv file that looks like this:
Answer: If you call .text on the monster_stats_table, it's going to turn it into one big chunk of text, as you see in your "Showing Problem" example. What you probably want to do is get the headers and data cells of the table into arrays that you can slice up as needed.
Since it looks like you are trying to transpose the information into a header row and data row, the following might be the way to go:
monster_stats_table = soup.find('table', class_='statBlock')
table_header_elements = monster_stats_table.find_all('th')
table_data_elements = monster_stats_table.find_all('td')

Then you can convert these to arrays of strings to write to your google sheet. I'm assuming that .append_row takes an array of strings.
headers = [header_element.text for header_element in table_header_elements]
data = [data_element.text for data_element in table_data_elements]

sh.append_row(headers)
sh.append_row(data)

Hopefully that gets you unstuck. Feel free to make the variable names useful for you.


Machine learning methods which takes time-to-event into account?

Question: My vague understanding is that machine learning methods are based on classification labels. How about a survival type of problem? That is to say, not only "have event" or "have no event", but also "time to event".
In statistics, we can perform e.g. Cox PH regression, but we can then only combine the multiple baseline characteristics in a linear manner (multivariable Cox analysis). If we want to look at a more advanced way to combine them, such as nonlinear, kernel-based, etc., is there corresponding machine learning methods which takes time-to-event into account?
Thanks for any comments.
Answer: It is a mistake to assume that the Cox proportional hazards model makes simple assumptions such as linearity.  All regression models have been extended for decades using regression splines, tensor interaction splines, and other approaches to allow for great flexibility in the low- to mid-dimensional case.  As others have said, penalization is instrumental in handling higher-dimensional cases.  [One problem is how to scale nonlinear terms when using penalization and regression splines simultaneously.]
Note also that the term 'multivariate' is inappropriate in this context as there is only one $Y$.
More to the original question, one of the amazing things about statistics is the ability of statistical approaches to extend models in various ways based on sound principles.  Faraggi and Simon (Statistics in Medicine, 1995) did just that to develop a likelihood function for obtaining an artificial neural network Cox model.
Comment: Multivariate **always** should refer to the dimensionality of the dependent/response variable.  _Multivariate analysis_ is the part of statistics dealing with more than one dependent variable.  When there are multiple predictors we use the terms _multivariable_ model or _multiple regression_.
Comment: I agree with you that statisticians have developed robust methods to handle time to event data vs. machine learning methods. Can you please let cite any head to head comparison between these two, so users can make an informed decision on which to use?
Comment: I wish I had a bibliography of such comparisons.  One good paper is http://www.citeulike.org/user/harrelfe/article/13467382
Comment: Thank you for your comments. Could you explain a little more why "the term 'multivariate' is inappropriate in this context as there is only one Y." I thought multivariate refers to the variables (the baseline characteristics). Thanks again.
Comment: A fix for the citeulike entry above: https://bmcmedresmethodol.biomedcentral.com/articles/10.1186/1471-2288-14-137
Answer: You may might be interested in Random Survival Forests and the corresponding R package randomForestSRC:
http://www.ccs.miami.edu/~hishwaran/papers/randomSurvivalForests.pdf
https://cran.r-project.org/web/packages/randomForestSRC/
I believe the main limitation of the approach is that it doesn't deal with time varying predictors.
Comment: I haven't heard about this one. I'd be very happy to give you +1 for this answer if you added some information about the general ideas behind this method.
Comment: I did a presentation of Lasso and RandoSurvivalForest in a R Users Conference in Spain this last year. Sorry, but the presentation is in Spanish, but it can be useful for R code and some general concepts: http://r-es.org/7jornadasR/ponencias/jesus_herranz.pdf
Comment: Note that if effects are mainly additive, random survival forests will easily be beat by additive regression methods.  Random forests require much larger sample sizes than regression to perform reliably.
Comment: Further, if I remember it correctly, random survival forests don't rely on the proportional hazards assumption, so they might be a good fall back when this assumption is violated and the sample size is big enough.
Answer: The majority of the linear models based in the likelihood function have extension to the Cox regression. For example, penalized regression models (lasso, rigde regression, elastic net) or partial least squares. In other hand, there are extensions from the classification trees to survival trees. This means all the ensemble methods based in trees are also extended to survival data in a natural way: random forest, bagging, gradient boosting machines, …. Finally, other methods, like support vector machines or neural networks have some theoretical versions for survival data, but there are difficult to apply in the practice.
Comment: Thank you. Will look into LASSO. Is this a commonly used technique in clinical studies?
Comment: I have used LASSO with the glmnet R package with genetic data in high-dimensionality problems successfully
Answer: Any linear survival analysis method can be straightforwardly kernelised to generate a non-linear equivalent.  I did something like this a while back for modelling the time-to-growth of microbial pathogens from spores in foods.
G. C. Cawley, N. L. C. Talbot, G. J. Janacek and M. W. Peck, Sparse Bayesian kernel survival analysis for modelling the growth domain of microbial pathogens, IEEE Transactions on Neural Networks, volume 17, number 2, pp. 471-481, March 2006. (www)


Complex Analysis - How a region's boundary changes under a complex function

Question:
Hi, I'm trying to solve this question. I tried plugging in the outer boundary for G (left picture), which is just the unit circle in the complex plane, but I can't simplify it into the form I want $\left(\frac{1}{3}e^{i\theta}\right)$.
$$f(e^{i\theta})=\frac{e^{i\theta}-\frac{1}{3}}{3-e^{i\theta}}=\frac{-2+3e^{i\theta}-\frac{1}{3}e^{i\theta}}{10-3(e^{i\theta}-e^{-i\theta})}=\frac{-2+3e^{i\theta}-\frac{1}{3}e^{i\theta}}{10-6cos\theta}$$
This is as far as I've been able to simplify this. Is this the right approach? Any help to further simplify is appreciated.
Answer: For a transformation like $ f(z)= \frac  {z-1/3}{3-z}$ which is a Mobius transformation it suffices to show that $3$ points of a circle transform to three points of another circle.
That proves that  the whole circle transforms to the other circle.
Pick three points on the boundary of $G$ such as $1,-1,i$ and show that their image is on a boundary circle of $H$.
For example,  $$f(1)= \frac {1-1/3}{3-1} = 1/3$$ which is on the boundary of $H$


Riemann Steiltjes Integral

Question: I have been stuck with this problem for a few hours. So far I have tried to prove that b- 1/n tends to b when n tends to infinity.
Let be $\alpha,\ f,\:[a,b]\to\mathbb{R}$ continous, such that f is Riemann Stieltjes Integrable
Show $[\int_a^{b-1/n}f\ d\alpha]_{n\in\mathbb{N}}\to \int_a^b f\, d\alpha$.
Comment: Use the fact that $f$ is bounded and note that $\int_{a} ^{b} f\, d\alpha - \int_{a} ^{b-1/n}f\,d\alpha=\int_{b-1/n}^{b}f\,d\alpha$
Comment: use the continuity of $\alpha$
Comment: I understand that. But how is it that the finite partitions of 1/n tend to that redult
Comment: How? Should I take the difference between the $\alpha(b)-\alpha(b-1/n)$
Answer: The easy case is where $\alpha$ monotone. Assume  WLOG that $\alpha $ is non-decreasing.  The integrand $f$ is continuous and, hence, bounded with $|f(x)| \leqslant M$ for $x \in [a,b]$.  Hence,
$$0 \leqslant \left|\int_{b-1/n}^b f \, d\alpha  \right| \leqslant M[\alpha(b) - \alpha(b-1/n)]$$
Since $\alpha $ is continuous we have by the squeeze theorem,
$$\lim_{n \to \infty}\int_{b-1/n}^b f \, d\alpha  = 0,$$
and the desired result follows from the additivity property of the integral,
$$\int_{b-1/n}^b f \, d\alpha  + \int_a^{b-1/n} f \, d\alpha   = \int_a^b f \, d\alpha  $$
A more general and difficult case is where we only have that $\alpha$ is of bounded variation.  For any $\epsilon > 0$ there exists $\delta > 0$ such that for any partition $P = (x_0,x_1, \ldots,x_m)$  with $\|P\| < \delta$ we have for any corresponding RS-sum
$$\left| \int_{b-1/n}^b f \, d\alpha - \sum_{j=1}^mf(\xi_j)[\alpha(x_j) - \alpha(x_{j-1})] \right| < \epsilon,  $$
which implies
$$\left| \int_{b-1/n}^b f \, d\alpha \right| < \epsilon + \sum_{j=1}^m|f(\xi_j)|\,|\alpha(x_j) - \alpha(x_{j-1})| \leqslant \epsilon +M V_{b-1/n}^b(\alpha). $$
Since $\alpha $ is continuous it can be shown with some effort (proved here) that the total variation function $x \to V_{x}^b(\alpha) $ is also continuous. Hence, $V_{b-1/n}^b(\alpha) \to V_b^b(\alpha) = 0$ as $n \to \infty$, and for every $\epsilon > 0$,
$$\lim_{n \to \infty}\int_{b-1/n}^b f \, d\alpha  \leqslant \epsilon,$$
which implies that again
$$\lim_{n \to \infty}\int_{b-1/n}^b f \, d\alpha  = 0$$
The most difficult case is where $\alpha$ has unbounded variation yet the RS-integral exists, but the first two cases cover what is usually considered for RS-integrals.
Comment: I am still unable to prove the case you mention at the end. Do you have a reference for its proof?
Comment: @ParamanandSingh: Not yet.  I thought I might have a counterexample but this proved to be incorrect.

Riemann Steiltjes Integral


How to find a bi-variate function from two univariate functions?

Question: I was analyzing the data from an experiment where the dependent variable $z$ is know to vary with two independent variables $x$ and $y$ are independent variables. The experiment was conducted in two ways.

Both $x$ and $y$ were varied and the values of $z$ observed. The relationship between $x$ and the average value of $z$ for different values of $y$ was found to be $z = f(x)$
Both $x$ and $y$ were varied and the values of $z$ observed. The relationship between $y$ and the average value of $z$ for different values of $x$ was found to be $z = g(x)$

At the end of the experiment, the individual relationships $z = f(x)$ and $z = g(y)$ but are known the combined relationship $z = h(x,y)$.
Question: Is there any standard way of finding the relationship $h$ such that $z = h(x,y)$?
In my specific example, in terms of $z$ can be represented in terms of $x$ using the cumulative distribution function of the standard normal distribution
$$
z = \frac{1}{2} + \frac{1}{2}erf \Bigg(\frac{x-a}{b\sqrt 2}\Bigg)
$$
where $erf$ is the error function. In terms of $y$, $z$ can be represented as
$$
z = \frac{1}{2}erfc \Bigg(-\frac{\log x-c}{d\sqrt 2}\Bigg)
$$
where $erfc$ is the complimentary error function. Here $a,b,c$ and $d$ are positive constants. I was able to find $h$ using numerical approximations. I would like to know if there an easier theoretical approach.
Answer: You cannot recover $h$ in general, but a good guess is
$$
\tilde{h}(x,y):=f(x)+g(y)-\mathbb{E}[f]
$$
In particular, if your observations are consistent in the sense that $\mathbb{E}[f]=\mathbb{E}[g]$ then this guess matches your observations in the sense that
$$
\mathbb{E}[\tilde{h}(x,y) | x ] = f(x)\\
\mathbb{E}[\tilde{h}(x,y) | y ] = g(y)
$$
You can easily verify that the guess agrees with the the true $h$ if and only if the true $h$ can be written as the sum of a function of $x$ and a function of $y$.


Android 2.1 (API 7) String to bytesArray java.lang.NoSuchMethodError: java.lang.String.getBytes

Question: In API 7 when try
val string = "string"
val bytes = string.toByteArray(Charset.forName("UTF-8"))

I get this exception:

java.lang.NoSuchMethodError: java.lang.String.getBytes

Is any way to get bytes from string without standard method? Looks like, conversion string to byte array starts with Api 8.
Answer: There are versions of getBytes() on String that work back to API Level 1, such as this one.
Comment: Possible, it's a feature of device, which i use for tests(eBook), but all methods of getBytes() ends with this exception.


How to create artificial data with one binary response variable?

Question: I want to check various classification model like random forest, tree, knn,etc. I used some bench marking data set but now I need to simulate my own data set with a binary response variable.
Comment: No, since your question is unclear. If you want to simulate a certain data generation model you can do so, but it unclear what exactly your question and your problem is.
Comment: Welcome to the site.

If you are asking about how to program this, then the question should go on StackOverflow. If you are asking about statistical properties, it should stay here. Please clarify.
Comment: I guess the question is the following: "How can one simulate data with binary response and features with predictive power", i.e. an artificial dataset for a binary classification problem. @ZKHAN can you clarify ?
Comment: We *can* help you, @ZKHAN, but we need to know a lot more about your situation & your goals. There are *lots* of ways to simulate data, eg, do you want to simulate data from a decision tree w/ certain properties so that you can check how well a k-nearest-neighbor algorithm can mimic the CART, something else? You may find the following blog post helpful: [how to ask a statistics question](http://www.statisticalanalysisconsulting.com/how-to-ask-a-statistics-question/).
Comment: Yes, I need an artificial data set produced through any model. The response should be binary and predictive features can belong to any distribution, e.g. normal, uniform. And I want to check the performance of knn and some other classifiers using those artificial data.
Answer: Have a look at the  R-package mlbench. Among various reallife datasets it contains generators for artificial ones, e.g.
mlbench.ringnorm(n=1000)

Another options is Data Mining Framework Rapidminer (java), which contains some more dataset generator for real-world-problems like Churning. For an overview, see this page (from the API) and search for "Generator".
Note that artificial datasets cannot be used to show that a classification algorithm is performing well. You may only explore certain properties of the algorithm or verify that a reproduction of another one's implementation is correct.
So if you want to perform a solid comparison, use real world datasets. You may find some here: Locating freely available data samples


echo ou print, qual realmente é a melhor opção?

Question: Sei das diferenças do echo ou print, mas em um projeto real em PHP qual é o mais indicado a se usar? Ou simplesmente tanto faz?
Answer: Depende da necessiade, tanto echo quanto print são  language constructs a diferença entre eles é que print sempre retorna 1(true) já o echo não retorna nada.
print
echo print('ola mundo');

A saida será ola mundo1. O print ainda pode ser usado com ternarios enquanto o echo não.
$p = ($idade <10) ? print ('menor') : print('maior'); //valido

$p = ($idade <10) ? echo ('menor') : echo ('maior'); //invalido,
Parse error: syntax error, unexpected T_ECHO

Comment: A vantagem que eu vejo nisso é em expressões do tipo ``, que com o `echo` não tem como fazer.
Comment: Nesse caso creio que também pode ser digitado com `echo` usando operador ternário: ``.
Answer: Um é praticamente apelido para o outro.
O print também existe em C, linguagem do qual o PHP se baseou fortemente, logo alguns livros ou cursos inicias de PHP, ou mesmo professores mais acostumados com C, podem usar print. Porém em geral como outros programadores PHP não iniciantes usam echo, então tende a ser interessante usar o echo fora da faculdade.
Ainda que o print exiba exemplos como print("Alô Mundo"), não é necessário por eles. Creio que a única diferença útil que o print poderia ter em relação ao echo é que ele retorna 1, porém se pretende deixar que outras pessoas deem manutenção no seu código, não tem real necessidade de explorar isso.
Veja documentação do echo em php.net e a documentação no print php.net.
Comment: Obrigado pela resposta Emerson.
Answer: São praticamente idênticos.
O print tem o detalhe de retornar um valor, 1 no caso de ter corrido. Assim pode usar-se
$printou = print('foo');

O echo permite concatenar variáveis/strings:
echo 'Olá!', ' mundo', '!'; // dá "Olá mundo!"
echo 'Olá!'.' mundo'.'!'; // dá "Olá mundo!"

O echo tem ainda a vantagem de ter um atalho quando se escreve misturado em html:
<?=$minhaVariavel?>

Comment: @phpricardo, pode ter, uma boa imagem (em Inglês) sobre isso: http://i.stack.imgur.com/Bgkl8.png , __[deste post](http://programmers.stackexchange.com/questions/151661/is-it-bad-practice-to-use-tag-in-php)__.
Comment: Mas concatenar variáveis e strings o print também faz
Comment: Obrigado por comentar Sergio.
Mas essa forma de atalho  não tem riscos futuros? Claro desde que o servidor esteja configurado devido ao <?php ...
Answer: A melhor opção é echo porque economizará um byte no tamanho do arquivo do seu código-fonte, a cada vez que for preferida no lugar de print (pois echo tem 4 caracteres e print tem 5 caracteres).
A melhor opção será print apenas se você precisar usar a expressão num ternário ou receber um valor de retorno.
Comment: Por que vale a pena economizar bytes no fonte em php?
Comment: Além do mais, `echo` nos remete ao [alien `Echo Echo` do Ben 10](http://2.bp.blogspot.com/_gYByhIgkwB4/TExH3a3GfhI/AAAAAAAAA8U/VMJdTmCU1Vo/s1600/echo-echo.png), enquanto `print` não nos faz lembrar de alien nenhum!
Comment: Por que desperdiçar bytes no fonte em php?
Answer: É melhor usar o echo.
Principalmente, porque echo aceita múltiplos  parâmetros; já o print não.
Que, no caso, geraria uma diferença considerável na hora de imprimir a instrução abaixo
echo  'Olá ', 'Meu nome é Wallace',
      ' e Eu tenho ', 30  - 6 , ' anos de idade', PHP_EOL;
      //Olá Meu nome é Wallace e Eu tenho 24 anos de idade

echo  'Olá ' . 'Meu nome é Wallace' .
      ' e Eu tenho ' . 30  -  6 . ' anos de idade'; // -6 anos de idade

Em relação ao print, a única vantagem que vejo em usá-lo ao invés do echo seria para simplificar uma expressão condicional para imprimir um valor.
Exemplos:
//Com `print`:

<?php isset($value) && print($value) ?>

//Com `echo` PHP 5.3 ou anteriores

<?php echo isset($value) ? $value : null; ?>

//No PHP 5.4+ já podemos fazer isso sem precisar habilitar o short_tags

<?= isset($value) ? $value : null; ?>

Mas essa é uma diferença bem pequena!
Comment: Eu ia responder sobre as virgulas, mas vi tua resposta, então +1


Let users assign particular roles to other users

Question: How can I let a "subadmin" to assign only particular roles to other users?
Just an example: my users can only use the forum if they have the "forum user" role. I would like to delegate the right to a "subadmin" to assign the "forum user" role to particular users, without letting this subadmin to be able to assign any other roles. Or I also want to let this subadmin assign the "article creator" role to others, etc.
Is there a module for that? Or do I have to create my own?
Answer: I hope Role Delegation module solves your problem !

This module allows site administrators to grant some roles the
  authority to assign selected roles to users, without them needing the
  administer permissions permission.
For each role, Role Delegation provides a new assign ROLE role
  permission to allow the assignment of that role
Comment: Wow, thank you! I just tried it, and this is simply perfect for the task! :)
Answer: You could do this with the Flag  and Rules modules.

Make a flag for each role.
Give the subadmin permissions to flag/unflag.
For each flag, add a rule that adds the relevant role on flagging and another rule that removes the relevant role upon unflagging.
Comment: +1, thank you for the idea! Finally I chose the Role Delegation module, which is a lightweight and really simple to use module, which is just enough. :)


Definite integral of $|\sin x|$ over $[0, 10\pi]$

Question: I'm trying to solve this and when I add both of the different signs together I ended by a result of 2, but it's not one of the choices, any help would be appreciated
$$\int_0^{10\pi}\ |\sin x| \, \mathrm{d}x$$
Comment: Is it $\sin|x|$ or $|\sin x|$?
Comment: The $x$ in your integration will always be non-negative. Thus it makes no difference to rewrite as $\sin x$
Comment: it's |sin x| sorry about that
Comment: https://www.desmos.com/calculator/kyl9wwwm1x
Comment: Tbh, I just have memorized that the area of a half-period of $\sin$ or $\cos$ is $2$. With this knowledge, the answer is clear.
Answer: $$
 \lvert \sin x \rvert
$$

You are making $10$ copies
$$
 \int_{0}^{10\pi} \lvert \sin x \rvert dx = 10 \int_{0}^{\pi} \sin x dx = 10 \cdot 2 = 20
$$
Answer: Note that $\sin $ is negative on $[\pi, 2\pi] \cup [3\pi, 4\pi] \cup\cdots \cup  [9\pi, 10\pi]$ and positive otherwise.  So $$\int_0^{10\pi} |\sin x| \, \mathrm{d}x = 5\int_0^{\pi} \sin x - 5 \int_{\pi}^{2\pi}\sin x \, \mathrm{d}x $$ by periodicity. But this is $5\cdot 2 - 5\cdot (-2) = 20$.

Alternatively, if you're fine with a more intuitive geometrical reasoning then note $|\sin x|$ consists of $10$ identical humps, each of area $\int_0^{\pi} \sin x \, \mathrm{d}x = 2$. So the total area is $20$.
Comment: it's |sin x| though would it make a difference?
Comment: oh okay sorry..
Answer: Notice from a quick look on a graph and recalling the period of sine that we have
$$\int_0^{10\pi}|\sin x|\ dx=10\int_0^\pi\sin x\ dx=10(\cos0-\cos\pi)=20$$
Answer: hint
$$\int_0^{2\pi}|\sin (x)|dx=$$
$$\int_0^\pi \sin (x)dx-\int_\pi^{2\pi}\sin (x)dx=$$
$$1+1+1+1=4$$
$$\int_0^{10\pi}|\sin (x)|dx=5\times 4=20$$
Answer: The integral
$$\int_0^{10\pi} \sin |x|dx= \int_0^{10\pi} \sin x dx=-\cos(10\pi)-(-\cos(0))=0.$$
On the other hand,
$$\int_0^{10\pi} |\sin x|dx = 10\int_0^\pi \sin (x) dx= 10(1+1)= 20$$


How to resize photo upload to exact dimensions with GD Library

Question: I have learned how to resize an image after uploading to server with GD Library.  It works perfect but I need the images to be resized to exactly 180 x 150px.  Depending on the original size of the image it will sometimes be less than 150 or less than 180.  How do I resize the images to be exactly 180px x 150px each time?
PHP Upload Script
// Access the $_FILES global variable for this specific file being uploaded
// and create local PHP variables from the $_FILES array of information
$fileName = $_FILES["uploaded_file"]["name"]; // The file name
$fileTmpLoc = $_FILES["uploaded_file"]["tmp_name"]; // File in the PHP tmp folder
$fileType = $_FILES["uploaded_file"]["type"]; // The type of file it is
$fileSize = $_FILES["uploaded_file"]["size"]; // File size in bytes
$fileErrorMsg = $_FILES["uploaded_file"]["error"]; // 0 for false... and 1 for true
$kaboom = explode(".", $fileName); // Split file name into an array using the dot
$fileExt = end($kaboom); // Now target the last array element to get the file extension
// START PHP Image Upload Error Handling --------------------------------------------------
if (!$fileTmpLoc) { // if file not chosen
echo "ERROR: Please browse for a file before clicking the upload button.";
exit();
} else if($fileSize > 5242880) { // if file size is larger than 5 Megabytes
echo "ERROR: Your file was larger than 5 Megabytes in size.";
unlink($fileTmpLoc); // Remove the uploaded file from the PHP temp folder
exit();
} else if (!preg_match("/.(gif|jpg|png)$/i", $fileName) ) {
 // This condition is only if you wish to allow uploading of specific file types
 echo "ERROR: Your image was not .gif, .jpg, or .png.";
 unlink($fileTmpLoc); // Remove the uploaded file from the PHP temp folder
 exit();
} else if ($fileErrorMsg == 1) { // if file upload error key is equal to 1
echo "ERROR: An error occured while processing the file. Try again.";
exit();
}
// END PHP Image Upload Error Handling ----------------------------------------------------
// Place it into your "uploads" folder mow using the move_uploaded_file() function
$moveResult = move_uploaded_file($fileTmpLoc, "uploads/$fileName");
// Check to make sure the move result is true before continuing
if ($moveResult != true) {
echo "ERROR: File not uploaded. Try again.";
unlink($fileTmpLoc); // Remove the uploaded file from the PHP temp folder
exit();
}
unlink($fileTmpLoc); // Remove the uploaded file from the PHP temp folder
// ---------- Include Universal Image Resizing Function --------
include_once("ak_php_img_lib_1.0.php");
$target_file = "uploads/$fileName";
$resized_file = "uploads/resized_$fileName";
$wmax = 180;
$hmax = 151;
ak_img_resize($target_file, $resized_file, $wmax, $hmax, $fileExt);
// ----------- End Universal Image Resizing Function -----------
// Display things to the page so you can see what is happening for testing purposes
echo "The file named $fileName uploaded successfuly.

";
echo "It is $fileSize bytes in size.

";
echo "It is an $fileType type of file.

";
echo "The file extension is $fileExt

";
echo "The Error Message output for this upload is: $fileErrorMsg";
?>

PHP Resize Script
<?php
// Function for resizing jpg, gif, or png image files
function ak_img_resize($target, $newcopy, $w, $h, $ext) {
list($w_orig, $h_orig) = getimagesize($target);
$scale_ratio = $w_orig / $h_orig;
if (($w / $h) > $scale_ratio) {
       $w = $h * $scale_ratio;
} else {
       $h = $w / $scale_ratio;
}
$img = "";
$ext = strtolower($ext);
if ($ext == "gif"){
  $img = imagecreatefromgif($target);
} else if($ext =="png"){
  $img = imagecreatefrompng($target);
} else {
  $img = imagecreatefromjpeg($target);
}
$tci = imagecreatetruecolor($w, $h);
// imagecopyresampled(dst_img, src_img, dst_x, dst_y, src_x, src_y, dst_w, dst_h, src_w, src_h)
imagecopyresampled($tci, $img, 0, 0, 0, 0, $w, $h, $w_orig, $h_orig);
imagejpeg($tci, $newcopy, 80);
}
?>

Comment: You may consider this [tutorial](http://code.tutsplus.com/tutorials/image-resizing-made-easy-with-php--net-10362) in regards to the matter. Also, look at this [article](http://www.sitepoint.com/imagick-vs-gd). If you can use imagick I would recommend that you do. One big drawback of the GD library (and there are several) is that you cannot natively resize animated GIF's and would require [imagecraft](https://github.com/coldume/imagecraft) or some other separate library.
Answer: The function you are using, ak_img_resize, is explicitly scaling the image (so as not to produce a distorted result):
...
$scale_ratio = $w_orig / $h_orig;
if (($w / $h) > $scale_ratio) {
    $w = $h * $scale_ratio;
} else {
    $h = $w / $scale_ratio;
}
...

To always resize to exactly 180x150, then replace the above lines with:
$w = 180;
$h = 150;

Note that this will produce a distorted result, unless the source image has exactly the same width-to-height ratio (1.2).
If you want an undistorted result then you'll need to resize and crop the excess height or width.


Degree of continuous mapping via integral

Question: Let $f \in C(S^{n},S^{n})$. If $n=1$ then the degree of $f$ coincides with index of curve $f(S^1)$ with respect to zero (winding number) and may be computed via integral
$$
   \deg f = \frac{1}{2\pi i} \int\limits_{f(S^1)} \frac{dz}{z}
$$
Is it possible to compute the degree of continuous mapping $f$ in the case $n>1$ via integral of some differential form?
Comment: The short answer is: Take the $n$-form $\omega$ that generates $H^n(S^n)$. Then $\deg f$ is the ratio of $\int f^* \omega$ over $\int \omega$.
Comment: See the beginning of this article: https://www.encyclopediaofmath.org/index.php/Brouwer_degree#References (Kronecker's definition: $$ \frac{1}{\operatorname{Volume} S^{n-1}} \int_{\partial K} f^* \omega $$
Answer: You could find some useful information (try page 6) here and here.


JSTL forEach doesn't loop

Question: I have strange problem with forEach in jstl. Here is my code
<c:forEach var="i" begin="1" end="5">
    Item <c:out value="${i}"/>

</c:forEach>

As you can see, it should print:  Item 1, Item 2, Item 3, Item 4, Item 5
But all what I get is - "Item" . Only one string without iterating variable value. I'm using Apache Tomcat 8 as server, and Intelij Idea as IDE.
Are any ideas?
Comment: check if your code is between  your code ...
Answer: 1- Check if you added core taglib at the top of the page
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>

2- Check if you added JSTL jar to webapp
Comment: It's a right answer. Thank you.
Comment: @snith mark this answer as accepted to help others who has the same problem to solve it

JSTL forEach doesn't loop


Drupal 8 get cart item programmatically

Question: I need to create pdf of user's cart items with custom header & footer. I decide to create custom module in which I can get cart items details. But I have no idea about how to do this? I have tried:
$store_id = 1;
$order_type = 'default';
$cart_manager = \Drupal::service('commerce_cart.cart_manager');
$cart_provider = \Drupal::service('commerce_cart.cart_provider');
$entity_manager = \Drupal::entityManager();
$store = $entity_manager->getStorage('commerce_store')->load($store_id);
$cart = $cart_provider->getCart($order_type, $store);
foreach ($cart-> getItems() as $order_item) {
    foreach($order_item->getPurchasedEntity() as $purchased_entity){
        print_r($purchased_entity);
    }
}

But it gives an array like
Drupal\commerce_product\Entity\ProductVariation Object
(
[values:protected] => Array
    (
        [variation_id] => Array
            (
                [x-default] => 432
            )

        [type] => Array
            (
                [x-default] => product_variations
            )

        [uuid] => Array
            (
                [x-default] => 87d27a77-4bc1-40ff-b3cf-ad3e949ce1b3
            )

        [langcode] => Array
            (
                [x-default] => en
            )

        [status] => Array
            (
                [x-default] => 1
            )

        [uid] => Array
            (
                [x-default] => 9
            )

        [product_id] => Array
            (
                [x-default] => 65
            )

        [sku] => Array
            (
                [x-default] => xx-uua
            )
        [price] => Array
            (
                [x-default] => Array
                    (
                        [number] => 22.000000
                        [currency_code] => USD
                    )

            )
        [field_order_no] => Array
            (
                [x-default] => Array
                    (
                        [0] => Array
                            (
                                [value] => PE-5070
                            )

                    )

            )

And many more protected objects.
I know I can get quantity, title & price easily using drupal function but how can I get few custom details from above array like field_order_no in above array, I have some unique attribute assigned to variation that I need to display in pdf?
Answer: As the top line suggests $purchased_entity is of of type "Drupal\commerce_product\Entity\ProductVariation" which is basically an entity.
All entities have a ->get('field_name') method.
So for your example to get 'field_order_no' you would do
$order_no = $purchased_entity->get('field_order_no')->getValue();

You can retrieve the value of any field via the ->getValue() method which returns an array.
Comment: Thanks! I had spent 6-7 hrs!!
Answer: $cart_provider = \Drupal::service('commerce_cart.cart_provider');
$cart = $cart_provider->getCart('default');
$order_items = $cart->order_items->referencedEntities();
foreach ($order_items as $order_item) {
    $product_variation = $order_item->getPurchasedEntity();
    $sku = $product_variation->getSku();
    $title = $order_item->title->value;
    $quantity = $order_item->quantity->value;
}

Drupal 8 get cart item programmatically


PHP Slim Framework v3 - Set global content-type for responses

Question: Is there a way to set the content-type to 'application/json' for responses globally in SLIM 3?
I tried the following things which did not work:
<code>$app->contentType('application/json');
$app->response->headers->set('Content-Type', 'application/json');
</code>
Answer: Middleware:
<code>$app->add(function ($request, $response, $next) {
    return $response->withHeader('Content-Type', 'application/json');
});
</code>


Como comparar String com String recebida em um .jsp?

Question: Tenho uma pagina html e ela manda um formulário com método tipo POST, pego os dados assim:
String email =  request.getParameter("user");

Quando comparo a string email com outra string contendo o mesmo texto ele me volta falso.
Pq isso acontece ? como posso resolver ?
Estou fazendo a comparação normal
if(email == "firstname.lastname@example.com"){
    out.println("executou aqui");
}

No caso "email@example.com" seria o mesmo valor da String que peguei no método post.
Comment: Como você está comparando?
Comment: Como você está fazendo a comparação?
Comment: if(email == "firstname.lastname@example.com"){
    out.println("executou aqui");
}

Este texto é o mesmo que estou mandando de outra pagina via POST
Answer: Quando você usa ==, você testa se dois objetos são idênticos, olha o exemplo:
String texto1 = "Mundo genial";
String texto2 = "Mundo genial";

No caso acima se você comparar com == você vai receber o valor desejado, mas como você esta trazendo essa informação, é o mesmo que fazer isso:
String s1 = new String("Mundo genial");
String s2 = new String("Mundo genial");

Nesse caso você está comparando conteúdo e a comparação tem que ser feita com equals,
boolean comparar = s1.equals(s2); // resultado = true
boolean comparar = s1 == s2; // resultado = false

Caso você queira continuar com o == você teria que de alguma forma apontar pro mesmo objeto, algo tipo assim:
String s1 = new String("Mundo genial");
String s2 = s1;

No caso acima se você fizer a comparação s1 == s2, o valor seria verdadeiro, pois eles estão apontando para o mesmo objeto.


SELinux Issue - git status fatal: Out of memory? mmap failed: Permission denied

Question: I have Centos 7.9 server running with Apache and Git, however if I do a
[root@a]# git status
fatal: Out of memory? mmap failed: Permission denied

But if Disable or Permissive the SE-Linux via below commands it start working fine.
setenforce Permissive

Any idea on how to fix this issue permanently with SELinux enabled?
Audit log says
node=a type=PROCTITLE msg=audit(1630636505.296:37076): proctitle=67697400737461747573
node=a type=MMAP msg=audit(1630636505.296:37076): fd=3 flags=0x2
node=a type=SYSCALL msg=audit(1630636505.296:37076): arch=c000003e syscall=9 success=no exit=-13 a0=0 a1=3ebd0 a2=3 a3=2 items=0 ppid=8008 pid=8156 auid=1001 uid=0 gid=0 euid=0 suid=0 fsuid=0 egid=0 sgid=0 fsgid=0 tty=pts0 ses=570 comm="git" exe="/usr/bin/git" subj=unconfined_u:unconfined_r:unconfined_t:s0-s0:c0.c1023 key=(null)
node=a type=AVC msg=audit(1630636505.296:37076): avc:  denied  { map } for  pid=8156 comm="git" path="/www/site/.git/index" dev="sda2" ino=540400 scontext=unconfined_u:unconfined_r:unconfined_t:s0-s0:c0.c1023 tcontext=unconfined_u:object_r:httpd_t:s0 tclass=file permissive=0

Comment: Root is normally unconfined. Can you provide the result of `id -Z`?
Comment: Check the audit log.
Comment: @MichaelHampton  I added the audit log into it says something abt
scontext=unconfined_u:unconfined_r:unconfined_t:s0-s0:c0.c1023 tcontext=unconfined_u:object_r:httpd_t:s0 tclass=file permissive=0
Comment: @MatthewIfe it says unconfined_u:unconfined_r:unconfined_t:s0-s0:c0.c1023
Answer: The problem is this file you're mapping:
/www/site/.git/index

This file has the type httpd_t however that isn't actually a legitimate file type but is a process (or domain type as its known) instead.
You should probably set the context of /www as being httpd_sys_content_t or if you want to allow the webserver to write to it httpd_sys_content_rw_t.
If I had to guess, I'm going to assume you did a chcon -t httpd_t on /www in error.
The best approach to fix this properly will be to reset and restore the file contexts:
# semanage fcontext -a -t httpd_sys_content_t '/www(/.*)?'
# restorecon -rv /www

This should set the correct context and prevent future context mishaps.
Then test the git status again to check it worked.
Comment: yeah i ran this, 'sudo chcon -Rv --type=httpd_t /www/'


What is a deviation vector?

Question: LINEAR ALGEBRA: I've looked online for this and can't find anything...
 What is a deviation vector and how do I compute them? (specifically how did my teacher get those vectors in part b?)
Here is the problem I'm referring to:

[4 points] Suppose we have nonnzero deviation vectors $\vec x,\vec y$ of two characteristics, such that $\vec x=c\vec y$. Show carefully what this implies about the correlation coefficient $r$ between the two characteristics.
[6 points] Find the correlation coefficient between the daily profit and number of paintings inside three CA coffee shops.

$$\begin{array}{|c|c|c|}
\hline
\text{Shop} & \text{Profit (in 100s)} & \text{Paintings} \\\hline
\text{A} & -1 & 1 \\\hline
\text{B} & -1 & 2 \\\hline
\text{C} & 2 & 3 \\\hline
\end{array}$$
Answer.

We have that:

$$r=\frac{\vec x\cdot\vec y}{\|\vec x\|\|\vec y\|}=\frac{c(\vec y\cdot\vec y)}{|c|\|\vec y\|\|\vec y\|}=\frac{c}{|c|}=\begin{cases} 1, & \text{if }c>0, \\ -1, & \text{if }c<0. \end{cases}$$

[6 points] We find deviation vectors $\vec x=(-1,-1,2)^T$ and $\vec y=(-1,0,1)^T$. This gives:

$$r=\frac{\vec x\cdot\vec y}{\|\vec x\|\|\vec y\|}=\frac{3}{\sqrt6\sqrt2}\left(=\frac{\sqrt3}{2}\right).$$

Question image
Answer: Deviation typically means $X-E(X)$, where $E(X)$ is the expected value/mean.
Notice that in the first column you have values $-1$, $-1$ and $2$. Their average is $0$, so after subtracting the average you get $\vec x=(-1,-1,2)$.
In the second column you have the values $1$, $2$ and $3$. The average of these values is $2$ after subtracting the average you get the values $1-2=-1$, $2-2=0$ and $3-2=1$. Your teacher written them into a single vector $\vec y=(-1,0,1)$.
The formula $$r=\frac{\vec x\cdot\vec y}{\|\vec x\|\|\vec y\|}$$
is then the formula for correlation coefficient. It is just written a bit differently. You can find this formula also in the Wikipedia article I linked above - in the section geometric interpretation. The example given there is very similar to this one. (Basically the only difference is that the Wikipedia article discusses uncentered and centered correlation coefficient.)

What is a deviation vector?


Use gtk status icon without memory leak

Question: I am trying to use a gtk status icon, but I do not know how to do that without causing memory leak.
<code>#include <gtk/gtk.h>

GtkWidget *window;
GtkStatusIcon *tray_icon;

static void activate (GtkApplication* app, gpointer user_data)
{
   window = gtk_application_window_new (app);
   gtk_window_set_title (GTK_WINDOW (window), "Window");
   gtk_window_set_default_size (GTK_WINDOW (window), 200, 200);
   gtk_widget_show_all (window);

   return; // <-- When this is commented out, valgrind finds memory leak.
   tray_icon = gtk_status_icon_new();
   gtk_status_icon_set_visible(tray_icon, TRUE);
   gtk_status_icon_set_tooltip_text(tray_icon, "abc");
}

int main (int argc, char **argv)
{
   GtkApplication *app;
   int status;

   app = gtk_application_new ("org.gtk.example", G_APPLICATION_FLAGS_NONE);
   g_signal_connect (app, "activate", G_CALLBACK (activate), NULL);
   status = g_application_run (G_APPLICATION (app), argc, argv);
   g_object_unref (app);

   // Here I am trying to clean it up somehow.
   gtk_status_icon_set_visible(tray_icon, FALSE);
   g_object_unref(G_OBJECT(tray_icon));

   return status;
}
</code>
When status icon is not used (see return statement with comment in the code), valgrind does not find any definitely or indirectly lost blocks. With status icon valgrind reports this:

definitely lost: 2,608 bytes in 7 blocks
indirectly lost: 13,745 bytes in 554 blocks

How should I correct the code to display status icon without causing memory leak?
Comment: Your code doesn't demonstrate that there is a memory leak, only that valgrind complains of one. GTK and other complex libraries use allocation patterns that are misreported as leaks by tools like valgrind. A simple way to test whether you're dealing with a real memory leak or not is to wrap the suspect code (and its cleanup) in an infinite loop and observe the process using `top` or equivalent. If its memory grows without bounds, then you have a leak on hand.
Comment: This deprecated code does abandon memory, about 8kb and about 0.1kb every time the tray icon is "destroyed" by g_object_unref and recreated, but it doesn't matter because an application should not be destroying and recreating tray icons, just setting them to visible or invisible, and once created a tray icon is considered "lost memory" or memory that will be allocated for the rest of the process, it's part of the design pattern to not be able to destroy the status icon and it's memory to be abandoned until deallocated at exit.
Comment: For what its worth, status icons are officially deprecated as of 3.14.
Comment: @BrianMcFarland Yes, they are. But I would like to use them anyway, because notifications do not suit my needs.
Comment: @Motomotes Whoa, thank you for your clarification of seven years old problem!
Answer: For my purposes the answer to this question was that there is no way to make valgrind report no losses on my leak free program. There are various suppression files available, including one referenced by the people at GNOME. There are a significant number of bugs posted against GTK+ relating to this concern, and at least a few stack overflow threads. I found that none of the suppression files I tried worked for me, and generating my own was a waste of time.
Comment: After more than a year I accept this as a solution. Now I understand why everybody is complaining about GTK. I think your answer describes situation well.

Use gtk status icon without memory leak


RADEditor's elements' CSS properties not getting overridden

Question: I added this in the head section of my page as told in the article..added the following two additional lines to get rid of the background image(RADEditor on my page is inheriting master page's bg image)
.reContentCell
        {
            background-image:none;
            background-color:White;
            }
            .reDropDown{color:Aqua;}

Why are the changes not taking place?
[EDIT]
added !important to both the properties above...still can't see no change
[EDIT]
I am using RADEditor in like MANY pages soo was wondering if I can do some coding in the Master Pages ..like in Master Page I can detect if there's some radEditor in any of the ContentPlaceholders..then I can add the CSS file to be used for that Editor so it doesn't inherit master page's CSS properties...so how do i go about it ?? How do I search for radEditor in Content pages and then add CSS to it ???
[EDIT]
I have already tried the following :-
ie adding CustomSkin's CSS classes to Editor
<telerik:RadEditor ID="Editor1" EnableEmbeddedBaseStylesheet="true" runat="server">

<CssFiles>

<telerik:EditorCssFile value="Skins/CustomSkin/Editor.CustomSkin.css"/>
<telerik:EditorCssFile value="Skins/CustomSkin/Editor.CustomSkin.css"/>
<telerik:EditorCssFile value="Skins/CustomSkin/Editor.CustomSkin.css"/>
 </CssFiles>

</telerik:RadEditor>

In the page's head section :-
I gave reference of CSS files...now its working fine..Editor is not getting screwed up or anything coz of Master page's CSS ...BUT what I want is some way to do this in the master page's code itself like I said above..plz help..thnx
[EDIT]
Master page's code behind :-
if(ContentPlaceHolders.Contains("what to type here??")){}

Intellisense is not showing Telerik RadEditor option in the drop down list
Is there some other way to add Editor's CSS files programmaticaly in master page's code behind??
Answer: use
.reContentCell, .reContentCell iframe
{
background-color:#FFFFFF !important;
}

because the original css file is adding a background colour to both the cell and the iframe.
Comment: its not working..actually the problem is not just the background image..even the heading tags are inheriting Master page's css' properties and I can't see no change in them either..I can't do something in mAster page's code behind ? like detect editor in its content pages and then add customized css classes to it ??
Comment: It seems like the editor is getting "screwed up" because it can't find any css properties for the editor and it's falling back on the other css in your page. So set a custom skin for the editor and then override the values you want to.
Comment: Michael I did just that!..plz read my updates above..custom skin thingy is working fine...but I want to add Editor's custom CSS files programatically in Master page's code behind so i don't have to add "CssFiles" attribute in each and every aspx page that is using the editor..there are so many


Ignore warning Python

Question: I have python script with following piece of code:
def refreshRoot():
    global root
    try:
        root.destroy()
    except:
        pass
    else:
        global root
    ...

This code returns SyntaxWarning which causes execution by double-clicking the icon to fail. Window simply doesn't open... So can I somehow prevent this warning from occuring?
Comment: It's *very* bad idea to ever ignore warnings. Fix the code instead: the second global declaration is unnecessary.
Comment: If I don't have second global declaration, it doesn't always consider `root` recreated afterwards global and it crashes...
Comment: Hmm. I'd have to see the rest of the code to diagnose that.
Comment: Have you tried `warnings` package? Check [this](https://docs.python.org/2/library/warnings.html#temporarily-suppressing-warnings) if you haven't. Or else compile with `python -W ignore ScriptName.py`
Answer: This will suppress all SyntaxWarning.
import warnings
warnings.filterwarnings("ignore", category=SyntaxWarning)

If you want to learn more, you can read this.

Ignore warning Python


I have 11 dalmatians. Can I find a subset of these 11 dalmatians such that the sum of the number of spots they have is divisible by 11?

Question: I have 11 dalmatians. Can I find a subset of these 11 dalmatians such that
the sum of the number of spots they have is divisible by 11?
My thoughts are that if there exist 1 dalmatian that has spots divisible by 11, then we find our subset (just take that dalmatian); On the other hand, if there does not exist such dalmatian, we could count the number of spots on each dalmatian and divided by 11, then we could get remainders from 1 to 10. We then put each dalmatian to the 10 bins according to the remainders calculated before.
Then by pigeon-hole principle, there is at least one bin that has at least 2 dalmatians. I am not sure how to proceed from here to solve the problem. I feel like I am missing some key pieces. Any help is appreciated!
Answer: HINT: Let $s_1,s_2,\ldots,s_{11}$ be the numbers of spots on the Dalmatians. For $k=1,\ldots,11$ let $t_k=s_1+\ldots+s_k$, the total number of spots on the first $k$ Dalmatians. Now apply your pigeonhole argument to the numbers $t_1,\ldots,t_{11}$. If one of them is divisible by $11$, you're done. If $t_k$ and $t_\ell$ have the same remainder on division by $11$, where $k<\ell$, can you find a set of Dalmatians that collectively have a number of spots divisible by $11$?
Comment: Thank you, Brian! This is helpful
Comment: @quant_to_be: You're welcome!

I have 11 dalmatians. Can I ﬁnd a subset of these 11 dalmatians such that the sum of the number of spots they have is divisible by 11?


How can I prove that $\operatorname{hess}r(iu,iu)\neq-\operatorname{hess}r(u,u)$?

Question: Let $\Omega\subseteq\Bbb C^n$ open, $z_0\in\Omega$, $r:\Omega\to\Bbb R$ twice real differentiable.
We know that $\Bbb C^n\simeq\Bbb R^{2n}$ is an isomorphism of vect.sp. So we think $\Bbb C^{n}$ as an $\Bbb R$-space, so it has dimension $2n$. A base for it is given by $z_1,\dots,z_n,\bar z_1,\dots,\bar z_n$. So $\Bbb C^n\simeq\Bbb C^n\times\overline{\Bbb C}^n$.
The Hessian matrix of $r$ in $z_0$ is the $2n\times2n$ matrix
$$
\operatorname{hess}r_{z_0}=
\left[
\begin{array}{cc}
\partial_{z_i}\partial_{z_j}r(z_0) & \partial_{z_i}\partial_{\bar z_j}r(z_0) \\
\partial_{\bar z_i}\partial_{z_j}r(z_0) & \partial_{\bar z_i}\partial_{\bar z_j}r(z_0)
\end{array}
\right]_{i,j=1,\dots,n}\;\;\;.
$$
Now we define the Levi form of $r$ as the block $(1,2)$ (or $(2,1)$, they are equal), i.e. the $n\times n$ matrix
$$
L_r(z_0)=
\left[
\begin{array}{c}
\partial_{z_i}\partial_{\bar z_j}r(z_0)
\end{array}
\right]_{i,j=1,\dots,n}\;\;\;.
$$
My book, writes as follows:
$$
\operatorname{hess}r_{z_0}=\sum_{i,j=1}^n\partial_{z_i}\partial_{z_j}r(z_0)\,dz_i\otimes dz_j+\\
+\sum_{i,j=1}^n\partial_{\bar z_i}\partial_{\bar z_j}r(z_0)\,d\bar z_i\otimes d\bar z_j+
2\sum_{i,j=1}^n\partial_{z_i}\partial_{\bar z_j}r(z_0)\,dz_i\otimes d\bar z_j
$$
(he thinks the hessian as the quadratic term in Taylor series of $r$ so he divides by $2$, but is not relevant) in this manner, both forms work on the same space (the matrix form should force the Levi form to work on $n$-tuple, but the hessian works on $2n$-tuples). I wrote the matrix form to be more clear.
My problem is the proposition 1.6.3. below. if I compute by hand, $\operatorname{hess}r(iu,iu)=-\operatorname{hess}r(u,u)$, so the proposition would be senseless.
Here I think $u\in\Bbb C^n$, but the hessian works on the $2n$-tuples, so I think the couple of vector he "eats" is $[(u,\bar u),(u,\bar u)]$ with $(u,\bar u)\in\Bbb C^{2n}$.
Where did I wrong? How can I see it by hand, without passing thru $\operatorname{hess}r=LP_r+L_r$ (otherwise it wouldn't be really explicative)?
Many thanks
Answer: Compute by hand again.  You must have just miscalculated.  When you plug $(iu,iu)$ into the real hessian the $(z,z)$ and $(\bar{z},\bar{z})$ part of the hessian gets a minus sign, the complex hessian acquires a $-i$.  So there is no direct relationship.


Is the statistical significance of a regression meaningful if it has poor out of sample performance?

Question: I want to determine the significance of a particular variable, among many confounders. If I fit a model on the training set and observe a small p value, should I discard the model because it extrapolates poorly on the test set (negative $R^2$ value), or should I keep it since I wasn't interested in predictions anyway?
Comment: It depends on your application and what your data looks like. How small is a "small" p-value? Are the extrapolated predictions *systematically* wrong, or do they nail down a trend through the middle of data that has a high variance?
Comment: p~1E-8. The question is does the particular variable, which is the time, predict the response variable or not. The explanatory variables are a mix of categorical and numerical. It's difficult to discern a trend purely using the particular variable because its effect is small; the other variables account for the bulk of the variance.
Comment: In that case I would say significance is still meaningful but unimportant. If you're trying to make predictions and the predictions are bad, then your model can't be good. It's possible that there is still a positive association between the predictor and the response; it's just too weak (relative to the noise in the data) to be of predictive value. Another possibility is that the underlying relationships in your in-sample and out-of-sample data are different. Also, did you plot the out-of-sample residuals? If they're symmetric you might still be okay.
Answer: It really depends on what you're interested in doing.
Statistical significance and out of sample performance are quite different criteria.
If your interest is in prediction, statistical significance isn't especially relevant.
On the other hand, if your interest is in whether some variable is more related to your response (after adjusting for the effect of other variables) than chance would allow (and that may a pretty limited set of circumstances), then out of sample predictive ability may not be especially important (that is, very weak effect may still matter).
What you should do first --- before you ever see data --- is carefully define your questions of interest and identify the particular criteria that speak to those questions. It's no use throwing this procedure and that procedure at your data and then saying 'wait, what am I doing this for anyway?'.
Figure out what you need your model to tell you. Then figure out how to do that.


In what way can a method provide better estimated than another method that already provides unbiased estimates?

Question: I read in Rand Wilcox's (2010) book:

"If homogeneity of variance cannot be assumed (with regard to regression), although the method of least squares still provides you with unbiased estimates of parameters (in this case, b1), you can obtain better estimates using other methods, such as weighted least squares"

My question is, if you are already obtaining an unbiased parameter, how is it that weighted least squares can improve on that?
Answer: You can't be more unbiased than unbiased, right. But maybe you can find weights so that the resulting estimator has smaller variance i.e. higher precision with all its benefits like smaller confidence intervals and stronger inference.
Same bias but smaller variance will provide an estimator with smaller mean squared error (= bias squared + variance).
Comment: Thank you for your reply Michael M. Would I then be correct in assuming that the benefits of this higher precision would be felt in more accurate probability values? That was the idea I got from your reply.
Comment: If you consider two-sided p values, then those derived from the more efficient estimator would be closer to 0 (because standard errors are smaller). That does not necessarily mean that the p values are less *inaccurate*, just smaller.
Comment: Hello Michael M, thank you very much for taking the time to provide this information, I really appreciate it. Have a nice day.


np.isnan for array in Python

Question: I have an array which I want to change into an array of True and False values to I can remove nan values.
When trying this using np.isnan as follows it's fine:
import numpy as np

a = np.array([1.,2.,np.nan])

a
Out[4]: array([ 1.,  2., nan])

np.isnan(a)
Out[5]: array([False, False,  True])

But when I try to do the same on my array, it doesn't work:
a
Out[9]:
array([73788400000.0, 80017300000.0, 83680400000.0, 84939700000.0,
       83877800000.0, 83911700000.0, 85368100000.0, 83808200000.0,
       85936400000.0, 85177800000.0, 82705400000.0, 82119100000.0,
       73935400.0, 64018400.0, 42796500.0, 43130000.0, 42637600.0,
       167911000.0, nan], dtype=object)
np.isnan(a)

Traceback (most recent call last):

  File "<ipython-input-10-f4b5b5e7f347>", line 1, in <module>
    np.isnan(a)

TypeError: ufunc 'isnan' not supported for the input types, and the inputs could not be safely coerced to any supported types according to the casting rule ''safe''

I suspect, given the error, this has something to do with the object type but I'm not sure how exactly.
Please note, when trying math.isnan, it only appears to take single values:
math.isnan(a)

Traceback (most recent call last):

  File "<ipython-input-11-6d4d8c26d370>", line 1, in <module>
    math.isnan(a)

TypeError: only size-1 arrays can be converted to Python scalars

Any help would be greatly appreciated!
Comment: Could you make use of pandas, and use `isnull()`? It checks for "NaN in numeric arrays, None/NaN in object arrays"
Comment: That worked but the solution below requires less switching between pandas and numpy arrays but thanks!
Answer: Convert your array to float and this will work:
import numpy as np

a = np.array([73788400000.0, 80017300000.0, 83680400000.0, 84939700000.0,
              83877800000.0, 83911700000.0, 85368100000.0, 83808200000.0,
              85936400000.0, 85177800000.0, 82705400000.0, 82119100000.0,
              73935400.0, 64018400.0, 42796500.0, 43130000.0, 42637600.0,
              167911000.0, np.nan], dtype=object)

res = np.isnan(a.astype(float))

# [False False False False False False False False False False False False
#  False False False False False False  True]

np.isnan for array in Python


Business statistics - variance and mean

Question:
The number of items produced in a factory is bell shaped and symmetrical with mean being 50. If variance = 25, what can be said about the proportion of week's production will be between 40 and 60?

This question has me stumped in terms of what it's asking and how to proceed. Any help would be greatly appreciated.
Answer: Try to answer the question "what % of the total is between 40 and 60?"  Or, "how far from 50 is 40 in terms of variance?"  Something like this:

The +1, +2, etc. in the figure is standard deviation, which is the root of variance.
The question is getting at how wide the bell curve is and what that means.  It also seems poorly worded.  Are you sure you copied the question correctly?
Comment: The "+1" in the figure is saying one standard deviation (not variance) away from the mean. The standard deviation is the square root of variance, which is 5 for your problem.
Comment: yeah I made sure to copy down the question exactly (english isn't my teachers first language). What do you mean by "in terms of variance"? 40 and 60 are both 10 away from 50. How does the 25 come into play here?
Answer: \begin{align} P \left( 40 \leq  X \leq 60 \right)
&= P \left( \frac{40-50}{\sqrt{25}} \leq  Z\leq \frac{60-50}{\sqrt{25}} \right) \\
&= P \left( -2 \leq Z \leq 2 \right) \\
&= \Phi(2) - \Phi(-2)\\ &= 0.9544997 \end{align}
Comment: Perfect. But ... this is a self-study question. The community's policy is to "provide helpful hints" for self-study questions, not solve it.
Comment: Oh. Sorry. I didn't look at the OP's name. Thanks for the advice.
Comment: @StudentT, thanks. Let me know if you need further hints.
Comment: I'm not the person who ask the question. I just want to mention about the policy here. I was warned by the mods myself before, because I solved someone else's homework.

Business statistics - variance and mean


Any idea what I should pay for a nyatiti?

Question: There aren't any available to try in my area, but I'd really like to pick one up.  The thing is, I have no idea what a reasonable price is.  There are a few online, but the prices vary (in one case, it looks like the same instrument is for sale for two wildly different prices, one at about $100 and the other site at about $500).
Basically, I've loved the first Ayub Ogada record for almost 30 years, and I want to make that noise. If anyone could point me in the right-ish direction, I'd appreciate it.
Some links:
http://bideetmusique.cdandlp.com/item/2/0-1916-0-1-0/117657503/kenyan-african-luo-traditional-instrument-nyatiti.html (Jojo records, $500)
http://www.groovecollector.com/mp/kenyan-african-luo-traditional-instrument-nyatiti/r/117657505/ (Also Jojo records, $100)
And so on, but you get the idea.
Answer: The price will vary based on who is trying to sell it to you and the age and condition of the instrument. Unfortunately, there is just no standard price.
They are hard to get. If you have connections and can do some travelling you can get one for $30. If you want one shipped to you from Nairobi you should expect to pay $300 or so.
Quality varies widely for things available online. There is a lot of tourist junk available that is listed as a nyatiti but is really just an ornament.
If you want, I might be able to help you get one.


ngRoute não funcionando corretamente

Question: Estou tentando criar rotas com o AngularJS para fazer uma Single Application. Eu consigo carregar a página principal que seria a /, mas outras que contém parâmetros não consigo. Tenho a URL http://localhost:3000/#/musica/5876a78078b88fe8662a188b e preciso carregar a view views/routes/visualizar.html, mas quando clico no link ele não sai da página raiz e a URL no navegador fica http://localhost:3000/#%2Fmusica%2F5876a78078b88fe8662a188b

        <title>Lista de músicas</title>
        <base href="/">
        <meta name="viewport" content="width=device-width, initial-scale=1.0">
        <meta charset="utf-8">
        <link rel="stylesheet" type="text/css" href="/assets/css/bootstrap.min.css">
        <link rel="stylesheet" type="text/css" href="/assets/css/style.css">

Comment: Experimente retirar o `$locationProvider.html5Mode(true);`, funcionou?
Comment: @GiancarloAbelGiulian Retirei, mas não funciona
Answer: tente utilizar o $location service
self.go = function ( path ) {
        $location.path( path );
};

Abrir musica

ngRoute não funcionando corretamente