Simple proofs module

Question: Let S be a set of three distinct integers. A be a nonempty subset of S and $\sigma _A$ be the sum of A.
Now prove that there exist two distinct non empty subsets $B,C\subset S$ with $\sigma _B\equiv \sigma_C \bmod 6$
Now I am able to figure out that we $\sigma _A$ could be the sum of any of these seven possibilities:
$$\{\{a\},\{b\},\{c\},\{a,b\},\{a,c\},\{b,c\},\{a,b,c\}\}$$
Now the book states that for each subset A of S, $\sigma _A$ is congruent to $0,1,2,3,4,$ or $ 5$ $\bmod 6$. How could I be sure of this?
Comment: If $n$ is any integer we try to divide $n$ by $6$.  We may fail, but we can always do it if you allow a remainder.  Specifically, we can always write $n=6q+r$ where $0≤r<6$.  Of course it follows that $r\in\{0,1,2,3,4,5\}$.  Also, it is clear that $n\equiv r \pmod 6$.
Comment: Does $Q_c=\sigma_C$?
Comment: To your second question, every integer is congruent to one of those numbers $\pmod 6$.  Those are the possible remainders on division by $6$.
Comment: Yes, lulu, I apologize for the notation something went wrong.
Comment: No problem.  In that case, your claim follows from the Pigeonhole Principle:  as you noted, you have $7$ subsets, hence $7$ sums, and there are only $6$ possible residue classes.
Comment: but why is  every integer congruent to one of those numbers (mod6). Could you explain a bit further?
Answer: For all $A\subseteq S$, you can be certain that $\sigma_A$ is congruent to 0, 1, 2, 3, 4, or 5 mod 6 because there are no other options for  $\sigma_A$. You could just as easily say $\sigma_A$ is congruent to

0, 1, or 2 mod 3
0, 1, 2, 3, ..., 198, 199 mod 200
0, 1, 2, ..., $n-1$ mod $n$ (in general)

It wouldn't make any sense to say $\sigma_A$ is congruent to 7 mod 6 because we just call that 1 again. $\sigma_A$ is the sum of integers, so it itself is an integer. Since congruence modulo $n$ is an equivalence relation on the integers, its equivalence classes partition the integers. Every integer must therefore belong to exactly one equivalence class, in this case 0, 1, 2, 3, 4, or 5. When talking about congruence, these are sets, not the actual integers. My professor wrote them as $[0]$, $[1]$, $[2]$, etc. where $[0]=\{...,-12,-6,0,6,12,24,...\}$, $[1]=\{...,-11,-5,1,7,13,...\}$, and so on, just to keep it straight in our heads.
Lulu also posted a comment which explains it another way using the division algorithm.
To continue the problem, the set of all subsets (i.e., the power set) of a set with size 3 is 7, which you showed by listing them all. The handy formula is $2^n-1$ where $n$ is the size of the set in question. So you have 7 sets that can be sorted into 6 equivalence classes. Intuitively, they must double up somewhere. Slightly more formally, this follows from the pigeonhole principle.
The pigeon hole principle states that if I have more pigeons than I have holes, there must be a hole with more than one pigeon stuffed in it. Or, if I have $p$ pigeons and $h$ holes with $p>h$, there exists at least one hole with greater than one pigeons in it. The contrapositive is even more intuitive. If all holes have 1 or fewer pigeons, then $p \leq h$. You could think of it as there are no onto functions from the set of pigeons to the set of holes.
For the case of your problem, replace "pigeons" with "sums of subsets of $S$" and "holes" with "equivalence classes modulo 6". Then using the pigeonhole principle, observe that at least one hole must have more than one pigeon in it. So if it has more than one, it must have at least two, and those are your two $\sigma$s.
The pigeonhole "proof" using the contrapositive isn't really a proof, just an appeal to intuition. If you're doing this for a class, you might be able to get away with just applying the pigeonhole principle if you've done something similar, or you could explain/prove it using the terms and assumptions you normally make in that class.

Simple proofs module


When to perform parameter type checking in JavaScript?

Question: For the most part, the library I'm developing is going to be consumed internally by one or more projects.  With that in mind, should I add logic that performs type checking on all parameters for functions I write, on some parameters or none?  To do selective type checking, I feel, would create an inconsitent feel to the API, to do it for all parameters would bloat the code, and to do it for none could lead to error messages that aren't helpful.  Any guidance as to why or why not would be appreciated.
Comment: _"is going to be consumed a single internally by one or more projects."_: Please clarify, I can't make heads or tails about that line.
Comment: I'm sure there's **many** opinions about this, but I try to leave type-checking out in as many cases as possible unless there's an absolute necessity for a certain type. I think the only place I do it is for passing functions, so I know I can call them. Just try using `===` for equality as it will not attempt to coerce types and will make sure two values are the same value and type. I like to think that if the user (might be yourself) isn't going to use the API correctly, they can expect weird results. Like Zeta said, documentation is important and can help prevent problems
Comment: @Cerbrus Sorry about that.  I blame the grammar error on fatigue and late hour (it's past midnight for me).
Comment: I assume you mean _"used internally by..."_? ;-)
Comment: @Ian Thanks for the feedback.  I originally went with some verbose type checking logic, but feel like, as Zeta mentioned, that documention is sufficient.
Answer: First of all, it is important that you document your API, even if it's only for internal use. It comes in handy if you need your code some years later.
In this documentation you can tell the user what type the parameters should be. An often used tool for documentation is doxygen:
<code>/**
* \brief Converts a string into a DummyObject
* \param str should be a valid string
*/
function str_to_dummy(str) {

}

/**
* \brief Converts an object into a DummyObject
* \param jsobj should be an object which contains at least
*        the following attibutes: 'height','length', 'size'
* \example json_to_dummy({'height': 12,'length': 15,'size': 11});
*/
function json_to_dummy(jsobj) {

}
</code>
Keep in mind that the user will experience an error message either way, either:
Parameter 'o' must be an object with attribute 'height'
or
ReferenceError: o.height is undefined
While it is nice to get a more verbose error, it often isn't necessary if you document your API correctly.
Answer: I guess it all comes down to how well you want to handle errors in your library. Can you live with the fact that someone passes you arguments of invalid type (even though, I'm assuming, documentation states clearly what he/she should pass)? If you're ok with that I would skip type checking to save on library size.
After all it's only client-side javascript if someone wants to tamper with it he will. There's nothing you can do about it.
Answer: I think you (almost) always should check or cast function parameters.
I just had smth. like this yesterday:
<code>foo("1");

function foo(myVar)
{
  return myVar+2;
}
</code>
So you should be careful. I believe it is a good reason.


Enable effect pedals by giving them power in different power chains

Question: My question is why or why not should I use the idea below:
So, regarding individual effect pedals in an signal chain, everybody has a different idea how to set the order, what to include when going on a solo or running clean, and again everybody has a different idea on how to do it.
My thought is a cheap and maybe lousy solution for my setup. It is to give selective DC power to specific pedals. Make a foot switched chain that gives power to the pedals that you want enabled for solo.
This would sure require true bypass ones.
eg: my setup
in () the ones I want to enter in the solo, in [] the booster which has no specific place and also may run all the time
<code>guit -> whah -> (overdrive) -> dist -> preamp -> (chorus) -> (delay) -> [clean booster] -> power amp
</code>
Downsides are:

Everything must be true bypass
Sudden spikes in noise or weird noises
Maybe delay to the time where the effect is fully operational
Not being sure if you have a pedal on or off (I mean its true bypass switch)
Changing to a second configuration easily done

Upside is:

Avoid the pedal dance...
Seriously, just press ONE switch and completely change configuration in pedals that could be anywhere in the chain
Would it work?
Comment: The problem has a solution: pedal switchers. Check out [this link](http://www.premierguitar.com/articles/19682-pedal-switcher-shootout?page=3) for a comparison of a few pedal switchers.
Comment: True bypass ,to me, means that the signal doesn't go through any circuitry when it's in its 'off' mode. That doesn't mean when there's no power to it, but it means when it's not switched 'on'. No power = no transmission of any signal.
Comment: @Tim, check my comment at Todd's answer
Answer:
Would it work?

No, it would not work.
The problem is if you leave a pedal bypassed, then applying or cutting the power to it does nothing. If you leave a pedal engaged, then applying power gives you the effected sound and cutting power gives you no sound at all. Even a true bypass pedal passes no audio when the pedal is "on" and the power is cut.
Also, a solution for this has already been invented
Although products that do this are not cheap. One fairly widely-known product for this is the Voodoo Lab Ground Control System, which lets you change your whole signal chain with one press of a footswitch.
The original inventor of these kinds of systems is almost certainly Bob Bradshaw, whose early products in this field have descendents being made by Custom Audio Electronics. At one time, Bradshaw was associated/licensed designs to Rocktron under the brand name Rocktron/Bradshaw. Rocktron still makes the Patchmate switcher and compatible MIDI controllers.
Comment: Hi again, you were completely right, it does not work, as when the pedal does nothing, I tried it out with my pedals. I had it wrongly in my mind on how true bypass pedals exactly work, sorry for my misbelief.
You have my upvote!
Comment: No need to apologize. Skepticism of stuff people write online is healthy. :-) Sorry your idea didn't pan out and thanks for the vote.
Comment: thanks for your answer Todd,
For if it would work, I am not sure if this is the case.. I mean having the pedal switch on and power off, the sound is as if the pedal does not exist.
Powering it on, resets the pedal switch ? maybe not in all pedals...
if it does not, then why wouldnt it work?
Comment: On all the pedals I have (which is a large number - 30+? and a mixture of true bypass and buffered), if the DC power supply is off, and the pedal is engaged, no sound will pass through at all. Maybe you can try it yourself on your pedals. Even if it did work, you would almost always get loud pops and strange noises when enganging and disengaging. And again, why deal with that? There are already ways to do this that don't involve something that won't work and would make horrible noises if it did work.
Comment: I will test it myself one of these days! (I have many mooer pedals) Just the question came to my head today waiting for a code compilation...
Now, whether it is useful or not, that is a whole lot different.. Sometimes we do some things just because we can and not because they are useful.. For the downsides, yep I included the things you mention
Comment: It's interesting that you would ask the question "would this work?" on Stack Exchange and then when someone answers the question, you assert that you think it would work despite the answer to the contrary. If you already believe it will work, why did you ask?
Comment: the fact that you answer does not mean that it is a correct answer and I have to accept it right at once. I have the right to criticize it. I didnt downvote or something, and I am not sure about the correct answer, that is why I am asking in the first place.
So its the two of us, I tend to believe it will work, you are certain it wont. Lets wait for other's opinions and reasonings
Comment: That's fair. The voting system is my favorite feature of Stack Exchange for that reason.
Comment: I agree it won't work, because of the reasons Todd gives. Your true bypass pedals will allow the "no-effect" signal through of course, but to get those pedals on you would still need to physically switch them in addition to applying the power. The best alternative is some kind of switcher as a few people have mentioned, thought these might be expensive. Perhaps a simple A/B pedal will work to select one of two different pedal chains.


how to create views with month and day in contextual filter

Question: Let suppose I have  actor content type, it has a birthday field (it is date ),
I want get all actor that has equal month and day of birth,I want to create a views with
birthsearch/%/%  path, and then I want pass  month and day to it ,
as exapmle birthsearch/02/25 , it should return all actor that birthday is 25 feb,I think contextual filter is good idea to achieve this but, by default drupal Granularity of date field  is

it is means I can restrict it to year and month, but I cant restrict it to day and month,
my question is how can I have views with month and day in contextual filter (passed to it by page Url)?
Answer: I achieve this with below solution,
create birthday field filter in views and set it to something fix =2000-02-02(not important later it will bypass),
then in my custom module  I implement hook_views_query_alter and change condition to what I want  "DATE_FORMAT(field_data_field_birth_date.field_birth_date_value, '%m%d') = :field_data_field_birth_date_field_birth_date_value"; and work correctly,and views page path is sbirthdaymd/% ( as example link will be something like sbirthdaymd/0524 )
/**
 * Implements hook_views_api().
 */
function mymodule_views_api() {
  return array(
    'api' => 3,
    'path' => drupal_get_path('module', 'mymodule'),
  );
}

/**
 * Implementation of hook_views_query_alter
 * @param $view
 * @param $query
 */
function mymodule_views_query_alter(&$view, &$query) {
    if($view->name == 'search_cast_by_birth_and_death') {
//        ym($view->query,'message');
        $url = parse_url(current_path());
        $temp = explode('/', $url['path']);
         if(!intval($temp[1]))
             $temp[1]="0406";
        if($view->current_display=='page_2'){
        $view->query->where[1]['conditions'][2]['field']="DATE_FORMAT(field_data_field_birth_date.field_birth_date_value, '%m%d') = :field_data_field_birth_date_field_birth_date_value";
        $view->query->where[1]['conditions'][2]['value'][':field_data_field_birth_date_field_birth_date_value']=$temp[1];
        }

     }
    }

Comment: Cheers - this is useful. I've built slightly on what you've done in another answer I've added but was just based on what you've put here (You can have a bounty in 6 hours!)...
Comment: Note that if you are using postgres instead of mysql the format functions (like date_format) are different, see: http://www.postgresql.org/docs/current/static/functions-formatting.html
Answer: I've just tested this with the post date field so assume it will work the same with a normal date field.
I added the field post date and then set the format to custom d and called the field post day.
I then added the field post date again and set the format to custom m and called the field post month.
These fields don't have to be visible so can be excluded from display.
I then added a contextual filter for "Content: Created day" and then "Content: Created month.
Now going to my_view/01/12 will show post that were created on 1st December.
Comment: tnx for your attention , but custom date field has not "Content: Created month" and "Content: Created day" in contextual filter options  :(
Comment: I see - those fields only appear for the post date and modified date, but not custom date fields.
Answer: Building on Zhilevan's answer I was able to add the where entirely programmatically. Doing it this way also meant I had to create the join programmatically.
/**
 * Implements hook_views_api().
 */
function misc_views_api() {
  return array(
    'api' => 3,
    'path' => drupal_get_path('module', 'misc'),
  );
}

/**
 * Implementation of hook_views_query_alter
 * @param $view
 * @param $query
 */
function misc_views_query_alter(&$view, &$query) {

    if($view->name == 'date_test') {

        $url = parse_url(current_path());
        $temp = explode('/', $url['path']);

        // Make sure month and date are zero padded.
        $month = str_pad($temp[1], 2, '0', STR_PAD_LEFT);
        $day = str_pad($temp[2], 2, '0', STR_PAD_LEFT);

        // Create join.
        $join = new views_join;
        $join->construct('field_data_field_date', 'node', 'nid', 'entity_id', array(), 'INNER');
        $query->add_relationship('field_data_field_date', $join, 'node');

        // Add where.
        $query->add_where_expression(0, "DATE_FORMAT(field_data_field_date.field_date_value, '%m%d') = :month_day", array(':month_day' => $month.$day));

    }
}

/**
 * Implements hook_views_pre_execute().
 */
function misc_views_pre_execute(&$view) {
    // This line outputs the generated SQL to the message area for debugging.
    dpq($view->build_info['query']);
}


How does the individual variance of a match of a game affect long term stat confidence?

Question: I play a 1v1 game mode where opponents shoot a giant football at each others goal.
I wish to increase my shots defended decimal.
<code>// EXAMPLE END MATCH RESULT
ME: 4 SHOTS - 4 GOALS
OPPONENT: 12 SHOTS - 2 GOALS

Shots defended = (OPPONENTS SHOTS - OPPONENTS GOALS) / OPPONENTS SHOTS
Shots defended = (12 SHOTS - 2 GOALS) / 12 SHOTS
Shots defended = 10 / 12
Shots defenced = 0.8333
</code>
This variable has a huge amount of variance between games, being anywhere from 0% - 100%.
What steps must be taken to work out how many games I need to sample to have a 90% confidence on the shots defended stat?
Answer: In my search for an answer, I have came across this tool.
It states:
<code>Sample size is calculated using the formula:

n = (Z2 � P(1 � P))/e2

where:
Z = value from standard normal distribution corresponding to desired confidence level (Z=1.96 for 95% CI)
P is expected true proportion
e is desired precision (half desired CI width).
</code>
So assuming expect my true portion of shots defended to be 0.65 and I am happy with a desired precision of + or - 0.05 and want a 90% confidence level then I need a total population (opponents shots in this case) to be 247.


How to print date in the format of mm/dd/yyyy in VB

Question: I need to print the date in the format of mm/dd/yyyy.
if the date is 4/24/2009 it should print the date as 04/24/2009.
that is zero padding is also needed..
I used date function to get the current date...but the date is getting in the format of m/dd/yyyy...
Comment: Which version of VB are you talking about?
Comment: `Date()` doesn't return it in any format. It returns a date which then uses your current locale settings when it is displayed.
Answer: Tested in the immediate window and is working for me (output as a comment)
Format(Now, "MM/dd/yyyy") '04/29/2009
Format(Date, "MM/dd/yyyy") '04/29/2009
Format(CStr(Now), "MM/dd/yyyy") '04/29/2009
Format(Date$, "MM/dd/yyyy") '04/29/2009
Format(CDate(Date), "MM/dd/yyyy")'04/29/2009

So whether it is string or datetime should not matter.
Edit: Saw your comment to Fredrik. It doesn't matter how it looks like when you save it to the db table (column date format would be a property of the db and not your program's (or vb's) responsibility). Just format the value as and when you retrieve it from the db.
Comment: The date data type, if unformatted, always displays as per system regional settings. You just need to format it when you want to display it.
Comment: Like what Fredrik said, even VB stores dates as a number, not a literal m/d/y string. Explanation of the storage here: http://www.codeguru.com/vb/gen/vb_misc/algorithms/article.php/c7495
Comment: if you try Msgbox(Format(Date, "MM/dd/yyyy")) it will work.. but i tried like... Dim dt as Date d = Format(Date, "MM/dd/yyyy") for this it wont work.
Comment: thanks a lot guys...
lastly i changed the data type of column to string...
now it is working fine...
Answer: Note that the "/" character in date formatting functions has a special meaning, as "date separator". This means that i may be replaced with the date separator for the current locale that the program is executed in (here in Sweden it would be replaced with "-" for instance). In order to ensure that you do indeed get the "/" character in the output, I think this would work (I don't have a VB installation to verify with):
Format(date, "MM'/'dd'/'yyyy")

Comment: yes you are write this will work only if the date type is of format string... but i am using Date format...
i am having one table..that has one column of data type date
so even if i convert the date to string as you mentioned.it will automatically will get convert to date ven i insert the value to tabel..
for eg:
dim dt as string
dt=Format(Date,"mm/dd/yyyy")'this will convert to 04/24/2009
but ven i insert this to table it will convert back to 4/24/2009 because that particular column is of type date
Comment: The reason it converts back when put in the table is that the table does not store the date as a string, but as a date object (which deep down is a numeric value). What you see is only a textual representation of it. I guess your DB software will automatically use your locales default to show the value to you. If you want it displayed in some other way in your application, you will need to format it before putting it into the control used for showing it.
Answer: just for the record, escaping the slash will work
Format(dt,"MM\/dd\/yyyy")
Answer: Try the next code:
Format(dt,"MM/dd/yyyy")

Answer: When you enter date in whatever format it will convert default value so do one thing that in access change your data type date/time to text then it can't affect to your work sure.
Answer: I also use VB6 and need to format date in my txt report
this works for me
Format$(Now, "yyyy-mm-dd-00.00.00")

but only if I declare date as string
Answer: You can try like this also depending upon your requirement
Dim strDate As String
Dim strDate1() As String
strDate = FormatDateTime(Now, vbGeneralDate)

If InStr(strDate, " ") > 0 Then
    strDate1 = Split(strDate, " ")
    Dim datDate1 As Date
    If Month(strDate1(0)) < 10 Then
        txtDate.Text = "0" + strDate1(0)
    Else
        txtDate.Text = strDate1(0)
    End If

Else

End If

Answer: Formatting DateTime as a string is straightforward. Often we use format patterns like "HH." But methods like ToShortDateString are also useful.
Example. First we get the current time through DateTime.Now. When you execute these code examples, the current DateTime will be different on your computer.
Here: A format string beginning with MMM (for the month) is used. Look at how the pattern matches up to the output of the program.
VB.NET program that uses format string with DateTime
Module Module1
    Sub Main()
        ' Use current time.
        ' ... Use a format.
        ' ... Write to console.
        Dim time As DateTime = DateTime.Now
        Dim format As String = "MMM ddd d HH:mm yyyy"
        Console.WriteLine(time.ToString(format))
    End Sub
End Module
Output
Feb Tue 21 13:26 2017
Answer: strDate = Format(strDate, "yyyy-mm-dd")
BillTime = Format(BillTime, "hh:mm:ss")


Cluster analysis not creating meaningful groups, just grouping together high/low scoring respondents

Question: To better learn cluster analysis I'm playing around with some Likert scale (agree-disagree) data I have, but the results I'm getting are basically useless. As the title suggests, rather than grouping respondents in any meaningful way, I'm just getting clusters of people who scored high on all questions, low on all questions, and somewhere in the middle. (That's an oversimplification, but you get the point). I've factor analyzed the questions and found a pretty clean factor solution with five factors, so there's reason to believe the questions should indeed be capable of dividing up the respondents.
Nonetheless, I've tried a variety of things and the solution always exhibits the same problem (e.g. I've tried different cluster methods, I've standardized the scores, I've run it with just a handful of variables I figured should work well, and I've run it with the regressed factor scores even though I know that isn't recommended).
My assumption is just that some people tended to agree more strongly across the board and it's confusing the cluster analysis. Indeed, the one thing I did that produced a more logical result was standardizing the scores by case rather than by variable, even though this approach seems far less common.
Is there any other explanation or any other way to deal with this issue?
Comment: I am puzzled why you seem puzzled here. People with similar scores will tend to be put in the same cluster, and all else is fine detail. Why is this surprising or disappointing?  If you want to find different patterns you may need to work with other criteria. For example, finding black and white (5s and 1s) versus everything is grey (3s, etc.) needs some different approach. (Cf. @Matthieu Rouyer's answer, posted independently.)
Comment: However, another way to think about it is that people classify themselves. if there are say 10 questions and you have 5 different answers, then there are $5^{10} \sim 10^7$ different profiles, whereas you presumably have many fewer respondents and it's unlikely that profiles that occur are equally common. So, that's a clustering with minimum technology requiring no assumptions. It might turn out to be a dead end, but it might also reveal some structure.
Comment: Fair enough. I should be a bit clearer. As evidenced by the factor analysis, the scale seems to have several latent factors with which different respondents tend to agree/disagree. In other words, given the data, it makes more sense that respondents who agreed with certain variables would tend to disagree with others, rather than just showing strong agreement across the board. I strongly anticipated, for example, Cluster 1 to agree highly with variables 1, 3, 5, and 7, and to disagree with 2, 4, 6, and 8, with Cluster 2 being the opposite.
Comment: Indeed. Naturally I can't comment on your clusters or variables, least of all when they are just numbered! But suppose you ask me whether I am interested in statistics and in sport and my answers are 5 (strongly agree) and 1 respectively then I am similar to anyone who answers in the same way. By the way, I am not aware that there's universal endorsement of factor analysis for this kind of data. I'd tend to use correspondence analysis as a strong preference. No doubt you're aware of some debates along similar lines.
Comment: More generally, clustering people [here] and clustering variables can't always be well served by the same technique but advocates of correspondence analysis seem positive that it can be.
Comment: I'm not especially familiar with correspondence analysis, so I will definitely look into it further. I appreciate your sports/stats example, but in the case of my data it seems highly probably that respondents who agreed with certain variables would tend to disagree with others.
Comment: Sure, and indeed I have little doubt that many people on this forum are not like me at all!
Answer: Have you tried subtracting the average score of each respondent in all of that respondent's answers?
This would give you the "within variation" for every respondent, akin to the technique used in the fixed-effect estimator in multivariate regression.
EDIT:
What you really have to think long and hard about is the question you want to answer with your analysis. For instance, Nick Cox's transformation in the comment to this post will lead to clustering people according to how strongly they express their opinion on some matter (in a way, the absolute interest they have in the subject regardless of which "side" they are on) whereas mine will lead to clustering according to the side they take.
Comment: You can cluster statistical people into those who believe in cluster analysis and those who don't. There are many highly successful, or at least very often used, classifications in science (classifications of elements, species, diseases, industries). It is an interesting question which cluster analyses have been adopted outside the particular papers in which they were discussed. (Mind you, you could say the same of regressions, etc.)
Comment: Hadn't tried that. I just gave it a quick test and it seemed to work well : ). Is this more common and/or preferable to taking the z-score for each respondent (by respondent, rather than by variable)?
Comment: Also, is there some sort of test I can use to demonstrate why this technique is useful (i.e., to overcome the noise of some people seemingly wanting to agree more strongly with everything)?
Comment: A variant of the same idea is to work with say $|\text{answer} - 3|$. Then (assuming a 5 point scale) everyone gets 0s, 1s or 2s. People with lots of 2s are going for the extremes; people with lots of 0s are going for the middle. I prefer this (at a distance) to subtracting means, because the numbers retain a closer link to the original scale.
Comment: Interesting, I'll have to play around with this.
Comment: I don't know much about cluster analysis to be honest so I cannot inform you much regarding how widespread and/or theoretically founded that approach is. What led me to give this answer is just that the way your problem was formulated reminded me of problems requiring fixed-effect estimators in multivariate regression.
Comment: "What you really have to think long and hard about is the question you want to answer with your analysis."

Yes, in the end I believe subtracting the average score makes more sense, even though the absolute value method is an interesting approach I hadn't thought of.
Comment: *Which* algorithm do you use?
Comment: @NickCox that isn't cluster analysis, but classification. :-D You can *classify* statisticians into those who believe in cluster analysis and those who don't. And I'm not aware of any good classification that was obtained by pure cluster analysis - most popular classifications were done (or at least edited heavily) by hand.
Comment: Finding clusters in the data is to me cluster analysis. I don't care if you need a special algorithm to do it; on the contrary, most special algorithms complicate as much as they simplify. The best classifications are those so evident that they don't need a technique to find them. If you have to strain and make arbitrary choices, you have (more nearly) a continuum better treated as such.


Add a Paypal button on the Shopify cart page

Question: I want to move the Paypal button from the Shopify Checkout to the Cart page.
The problem I have is that the Paypal button on the Checkout has a token that's only available on the Checkout page.  I've also checked the Shopify documentation and there is no mention on how to retrieve this token.
Answer: If you have the paypal express enabled in payment gateway. This code should let you display the Paypal button in cart page.
{% if additional_checkout_buttons %}

{{ content_for_additional_checkout_buttons }}

{% endif %}

Answer:
Login to your Shopify admin
Go to Themes page
Click Template Editor
Click cart.liquid and open it in online code editor
Search for name="checkout"
Please include the following code.
{% if additional_checkout_buttons %}

 Or Checkout using:
{{ content_for_additional_checkout_buttons }}

{% endif %}
Save your changes.
Comment: Please check this[URL](http://stackoverflow.com/help) it will be handy to lift your content quality up


What's the equivalent of cache_clear_all()?

Question: What's the equivalent of cache_clear_all() in Drupal 8?
Answer: You can use Cache api. It would be somthing like
\Drupal::cache('bin')->invalidateAll();

Or if you want to remove the entries and not just invalidate them:
\Drupal::cache('bin')->delete('variables')

where bin is a valid cache bin such as menu, render, page ...etc.
Comment: limited to the bin, but everything in that, yes. cache_clear_all() had a about 7 different functions depending on what you passed in and that example above cleared a specific entry, so the equivalent would be  \Drupal::cache('bin')->delete('variables')
Comment: invalidateAll() invalidates all, not just a specific key, that would be delete() or deleteMultiple(). You most likely don't want to use invalidate* but delete* because the invalidate methods just mark it as invalida but don't actually delete it. That only makes sense if you have a use case whre you might want to load that with $allow_invalid = TRUE
Comment: But it's limited to the bin passed to invalidate?


GCM: Using same account on multiple devices - what happens?

Question: I have a question concerning Google Cloud Messaging.
When I install the same app, on two different google android devices with same google account - then both will register themselves in gcm. i am storing their regId on server.
but what happens when I send to one of the regid a message - will the second get the message too? -will one of the regid be canonical? (because of same google account on device like the other - or are they treated completely different?)
Answer:
What happens when I send to one of the regid a message - will the second get the message too?

Well, no. This is because GCM not only takes into account just the Google account that you use on your phone but also identifies the particular device and the particular app you are running on it. GCM id is unique for a any given app on any given device. That is how the cloud identifies which device to push notifications to. So even if you sign in to two different devices with the same account, both will register with different keys. You use this key to identify the individual device/app.
Go to the official documentation on this to get the full info.
Answer: Sounds like you want to use User Notifications. The docs are pretty straightforward. Basically you'll need to do some work on the server side to map multiple registration ids to one "notification_key" then you use this key when pushing to Google.
Google handles pushing to the multiple devices and will even do some nice syncing type things for you.


hotplugging drives from a fibre-channel cabin reports wrong size

Question: First thing, we are not even sure this is a udev problem, but we need somewhere to start asking... We have a Hitachi fibre-channel SAN serving volumes to a couple of machines running ubuntu server 12.04 amd64.
For mapping purposes we use the udev-generated /dev/disk/by-id identifiers
...
/dev/disk/by-id/scsi-1HITACHI_750505270125
/dev/disk/by-id/scsi-1HITACHI_750505270125-part1
/dev/disk/by-id/scsi-1HITACHI_750505270126
/dev/disk/by-id/scsi-1HITACHI_750505270126-part1
...

where the last 4 digits (0125, 0126, 0127...) identify the LUNs created on the Hitachi, so we know which physical volume we're accessing.
We found a weird problem, where we had a 1.1T volume on LUN 125 and we broke it down into smaller chunks on the cabin side. After reassigning one of the new drives to the server it seems the volume size is cached (see the 1150.5 GB size)...
root@server1:~# fdisk -l /dev/disk/by-id/scsi-1HITACHI_750505270125

Disk /dev/disk/by-id/scsi-1HITACHI_750505270125: 1150.5 GB, 1150514364416 bytes
255 heads, 63 sectors/track, 139875 cylinders, total 2247098368 sectors
Units = sectors of 1 * 512 = 512 bytes
Sector size (logical/physical): 512 bytes / 512 bytes
I/O size (minimum/optimal): 512 bytes / 512 bytes
Disk identifier: 0x00000000

                                      Device Boot      Start         End      Blocks   Id  System
/dev/disk/by-id/scsi-1HITACHI_750505270125-part1              63  1048575999   524287968+  83  Linux

The weird part is that we have the same volumes connected to a different machine. They are not active, but they are still visible. We saw the same behaviour, but after rebooting the drives look as they should (see the 536.9 GB size):
root@server2:~# fdisk -l /dev/disk/by-id/scsi-1HITACHI_750505270125

Disk /dev/disk/by-id/scsi-1HITACHI_750505270125: 536.9 GB, 536870912000 bytes
255 heads, 63 sectors/track, 65270 cylinders, total 1048576000 sectors
Units = sectors of 1 * 512 = 512 bytes
Sector size (logical/physical): 512 bytes / 512 bytes
I/O size (minimum/optimal): 512 bytes / 512 bytes
Disk identifier: 0x00000000

                                      Device Boot      Start         End      Blocks   Id  System
/dev/disk/by-id/scsi-1HITACHI_750505270125-part1              63  1048575999   524287968+  83  Linux

The funny part is that we partitioned the drive on the second server (server2), the one that sees the right size, and on the first server (server1) we can see that partition, even though the actual drive size is still the old one. We even formatted it and mounted it on server2, wrote a txt file, unmounted it, remounted it on server1 and, sure enough, we can see and access the txt file.
Looks like somewhere along the way someone is caching volume sizes?
Just in case, after detaching and reattaching the drives we re-scan the LUNs and run udevadm trigger to refresh the udev tree...
We are not really comfortable using the drives with this disparity, and if we need to reboot to get the system to show real sizes we lose all the advantages of hotplugging... Any ideas on how is this happening and is it safe to use those volumes without restarting?
As a side question, when we detach the drives from the fibre cabin, we run udevadm trigger and looks like udev just adds new drives (devices), but it doesn't remove devices that are gone... is that supposed to be that way?
Comment: is partprobe installed on your system? It's used to reread partition table without rebooting.
Comment: Didn't know about this utility... I ran it on that particular drive (partprobe -s /dev/disk/by-id/scsi-1HITACHI_750505270125), but still shows the same wrong size
Comment: what kind of hba you have? qlogic?
Comment: From lspci: Emulex Corporation Zephyr LightPulse Fibre Channel Host Adapter (rev 02)
Answer: There are several command that come to play as there are multiple layers involved.
For update / rescan
FC
To just simply scan the bus run:
echo "1" > /sys/class/fc_host/hostXYZ/issue_lip
echo "- - -" > /sys/class/scsi_host/hostXYZ/scan

If you know the bus/target/lun in advance you can just say:
echo "b t l" > /sys/class/scsi_host/hostXYZ/scan

you replace b t l with bus target and lun numbers.
A SCSI specific command to update a shrink/grown size of a disk is
echo 1 > /sys/block/sdX/device/rescan

You need to know the corresponding drive canonical name e.g. sda.

To remove / delete a disk
(you need to replace the sda and 0:0:0 obviously)
umount everything from that disk
Remove from the SCSI layer
echo 1 > /sys/class/block/sda/device/delete

Remove from the FC layer
echo 1 > /sys/class/fc_transport/target0\:0\:0/device/0\:0\:0\:0/delete

Now you can safely remove it from the SAN.


McNemar-Bowker test for comparison of two measures

Question: I am comparing two versions of a survey (an original, and a modified) and was wondering if the McNemar-Bowker test is appropriate.
The survey(s) ask respondents to indicate whether they've had an experience (in this case, unwanted sexual contact) since the age of 14.  Respondents have four answer choices to indicate the frequency which they've had a certain experience, coded the following way:
<code>  "never"
  "once"
  "twice"
  "three or more times"
</code>
My hypothesis is that participants will indicate an increased number of experiences when given the modified version, as compared to the original.  In this instance I am looking at the rates which men admit to having perpetrated acts of unwanted sexual contact; with the hypothesis that the modified version will ellicit increased rates of admitted perpetration compared to the original version.
My data do in fact show an increase in male admittal-rates on the modified version.
<code> MALE ORIGINAL     (n)                      MALE MODIFIED     (n)
 "Never" =         281                      "Never" =         270
 "Once" =           18                      "Once" =           18
 "Twice" =           7                      "Twice" =           8
 "Three +" =         7                      "Three +" =        17
  Total admittal =  32                       Total admittal =  43
  Total n =        313                       Total n =        313
</code>
So, now i want to test for significant difference between response rates on these two surveys to see if the increase of admittal on the modified version is statistically significantly higher.  This is a repeated measures design, so each participant took both survey versions.
I am wondering if the McNemar-Bowker test is appropriate for my data (above)?  My plan is to arrange the table as such:

<code>                                 ORIGINAL SURVEY

                      |"Never" | "Once" | "Twice" | "Three +" | TOTAL |
                      |________|________|_________|___________|_______|
               "Never"|  261   |   7    |    2    |     0     |  270  |
                      |________|________|_________|___________|_______|
                "Once"|   12   |   5    |    1    |     0     |   18  |
                      |________|________|_________|___________|_______|
               "Twice"|    3   |   4    |    1    |     0     |    8  |
                      |________|________|_________|___________|_______|
             "Three +"|    5   |   2    |    3    |     7     |   17  |
                      |________|________|_________|___________|_______|
                TOTAL |  281   |   18   |    7    |     7     |  313  |
                      |________|________|_________|___________|_______|
</code>
MODIFIED
      SURVEY

When I run the above analysis in SPSS crosstabs, I get a McNemar-Bowker chi-square value of 13.316, df = 6, p = 0.038.  So my questions are:

Is the McNemar-Bowker appropriate for my data and hypothesis?
With
the resulting p value of 0.038 can I now say that the results from
the two surveys are significantly different -- with the modified
version showing an increase in male admittal?
Answer: McNemar-Bowker test of symmetry of k X k contingency table is inherently 2-sided: the alternative hypothesis is undirected. So, in general case it cannot be used to test a one sided alternative that subdiagonal frequencies are larger/smaller than superdiagonal frequencies. But since in your case the differences are consistently in favour of subdiagonal frequencies you can use the test for the directional inference.
The Bowker test is chi-square asymptotic-based and hence is for "large sample" - I've read somewhere (sorry don't remember where, so I'm not quite sure) that the sum in any two symmetric cells, if it is not 0 (the test ignores 0-0 cell pairs altogether), should be at least 10. Clearly, this isn't your case - you have only one pair of symmetric cells with the large sum. There exists an exact version of the test (see) but not in SPSS. But you can bypass the problem if you merge "Once", "Twice", "Three+" categories. Then you'll have the dichotomous case for which Bowker test becomes McNemar test with exact p-value easily computed (SPSS does it).
You might want also to consider some alternative tests of symmetry of a contingency table. Because it is questionnable whether your inquiry is isomorphic to what McNemar-Bowker tests. It tests if every off-diagonal cell is equal (in population) to the cell symmetric to it. Might it be that comparing the subdiagonal and the superdiagonal sums is more apt here?
Comment: A reference for the rule of thumb "sum of each cell is at least 10" regarding the chi^2 approximation can be found in:
Krauth, J. (1973). Nichtparametrische Ansätze zur Auswertung von Verlaufskurven. Biometrische Zeitschrift, 15(8), 557-566.
Unluckely it is in German, however on page 561 equation 18 it is mathematically described.
The text immediatly above states: "The requirement for the legitimacy of the chi^2 approximation, which is anlog to (13) is: (n_ij + n_ji)/2 >= d."
Going back to (13) on page 560, one finds immediatly above the equation: "usually it is set to d=5"


Two slopes between 0 and 1, neither different from 0, could they be different from each other?

Question: I'm reading a paper that does not report the coefficients from two OLS regressions. In both cases there is 1 response variable and 1 predictor variable.  The predictor variable is the same in both cases. I know the subject matter of the paper well, which leads me to believe that the means of the slopes are almost certainly between 0 and 1. Although the slopes for these two regressions are not reported, the author does report that neither slope is significantly different from 0 (p ≥ 0.05).
If neither slope is different from 0, but both slopes are between 0 and 1, could the slopes be different from each other?
To try to figure this out, I did a quick test in R.  I used two slopes that were very different (0.99 and 0.01), but chose s.e.'s for each that would make them barely "insignificant". To compare the slopes, I used the formula from the answer to THIS question.
pnorm(
  (0.99 - 0.01)/ #difference between means
  sqrt(0.61^2 + 0.0062^2), #sqrt of sum squares of s.e.'s
  lower.tail=FALSE
)

OK, so this quick-and-dirty test suggests that the two slopes in the author's analysis can't be different.
Is it necessarily true that if two slopes are between 0 and 1, and neither different from 0, that they cannot be significantly different from each other?
Answer: It depends on how you do the testing.  For instance, consider this model for the three variables $x$, $y_0$, and $y_1$:
$$\cases{
  \mathbb{E}[y_0] = \beta_{0} + \beta_{1}x \\
  y_1 = y_0 + \gamma x
}$$
where $\beta_0$, $\beta_1$, and $\gamma$ are parameters and $\gamma$ is the difference in slopes.  Evidently
$$  \mathbb{E}[y_1] = \mathbb{E}[y_0 + \gamma x] = (\beta_{0} + \beta_{1}x) + \gamma x = \beta_0 + \beta_2 x$$
with $\beta_2 = \beta_1 + \gamma$.  Then it is possible for estimates $\widehat{\beta}_1$ and $\widehat{\beta}_2$ to be indistinguishable from zero while determining, via regressing $y_1-y_0 = \gamma x$ against $x$, that $\widehat{\gamma}$ differs significantly from zero.  The key idea is that $y_1$ and $y_0$ are not independent.

As an example here are simulated data in R:
n <- 10
x <- 1:n
delta <- x / n^2
y.0 <- residuals(lm(rnorm(n) ~ x)) + delta/2
y.1 <- y.0 + delta
pairs(cbind(x, delta, y.0, y.1))

Neither of the regressions $y_i \sim x$ is significant ($\widehat{\beta}_0 = 1/200,$ $p=0.937$ and $\widehat{\beta}_1 = 3/200$, $p=0.812$):
> summary(lm(y.0 ~ x))

            Estimate Std. Error t value Pr(>|t|)
(Intercept)  0.00000    0.37903   0.000    1.000
x            0.00500    0.06109   0.082    0.937

> summary(lm(y.1 ~ x))

             Estimate Std. Error t value Pr(>|t|)
(Intercept) 5.266e-17  3.790e-01   0.000    1.000
x           1.500e-02  6.109e-02   0.246    0.812

The regression of $y_1 - y_0 \sim x$ is extremely significant ($\widehat{\gamma} = 1/100,$ $p \lt 2\times 10^{-16}$):
> summary(lm((y.1 - y.0) ~ x))

             Estimate Std. Error   t value Pr(>|t|)
(Intercept) 2.633e-17  1.415e-17 1.860e+00   0.0999 .
x           1.000e-02  2.281e-18 4.384e+15   <2e-16 ****

Comment: I *think* I can agree with that, provided we understand "y-axes" to mean "dependent variables."  This phenomenon is akin to the difference between an unpaired and paired t-test: the test in your question is a legitimate one, analogous to an unpaired t-test, but it lacks power to detect true differences in slope when the variables are (conditionally) positively correlated. Testing the slope of the regressed *difference* is the analog of performing a t-test of a difference of paired variables to see whether it is zero.
Comment: Just to be sure I get the idea, you're saying that the slopes could be different if the y-axes in the two regressions are correlated, right? Thanks a ton for the answer, this is definitely a good piece of information to keep in mind!
Comment: That is what I meant, thanks for the additional explanation :)


Combine folder contents to PowerPoint

Question: I'd like to take a folder and combine all content into one PowerPoint slideshow by use of only the pathname to the folder.  I don't know if this is even possible.
The content of the folder would be multiple other PowerPoint presentation with designators to identify the order (01 - 11, etc.).  The source formatting would need to be maintained.
Any input would be appreciated.
I know i can load a single PowerPoint and insert another file, but when you start working with many files, it becomes quite the task.
Answer: It's possible.  You'll need to use Dir repeatedly to get the names of the files in the folder and store them in an array.  Sort the array to make sure they're in the right order, then use something like this once for each file in the array to insert the slides:
<code>Dim oPres As Presentation
Dim oPresTemp As Presentation
Dim x As Long
Dim oSl As Slide
Dim oTmpRng As SlideRange

Set oPres = ActivePresentation
Set oPresTemp = Presentations.Open("C:\SR\CurrentProjects\Client\GetMyGraphic\FUNNEL\Funnel_0032.pptx")

For x = 1 To oPresTemp.Slides.Count
    oPresTemp.Slides(x).Copy
    Set oTmpRng = oPres.Slides.Paste
    Set oSl = oTmpRng(1)
    oSl.Design = oPresTemp.Slides(x).Design
Next

oPresTemp.Close
</code>
There's a bit more to it than that, but it's a start.  I'd also read through the code here for further ideas:  http://skp.mvps.org/pptxp001.htm

Combine folder contents to PowerPoint


when add-on test is necessary? better diagnosis strategy

Question: Suppose there are two types of tests available. Test A: low-cost, but relatively less precise; Test B: high-cost, but more precise. Test B can be considered as the good standard with 100% accuracy. Suppose there is a group of patients with different sex, age, gender and race. The question is, which patient should be recommended to the high-cost Test B after the initial screening with Test A. Another complexity is that the precision of Test A varies from individual to individual, affected by sex, age, gender, and race.
The literature I currently reviewed is always trying to come up with the best strategy at the population level instead of individual patient level. That is a common cutoff point for all the patients regardless of their age, gender, etc. What really interests me is to come up a personalized strategy.
Any idea which literature I should look into?
Answer: Since nobody has answered on a week, I'll try a partial answer.
The personalized strategy you propose is already being used. For example, it was used in the widely performed triple trest for pregnant women - although nowadays it is a bit outdated.
What you want to know after the cheap first test (test A) is the conditional probability of illness given the outcome of test A and all other relevant patient circumstances. With that probability you can do a cost-benefit analysis of test B and decide if it's worth.
After triple test, probability of some fetus problems was computed and checked against risk (and cost) of more invasive tests to decide if it was worth taking such tests.


How to test for significant differences in R?

Question: I want to test whether there are differences in the parameters of the Bass diffusion model (m, p, q) for Food products compared to Non-food products. My data looks as follows (including 3223 products, both food and nonfood and many more variables such as product category etc.):
   barcode     m          p           q           Food
   12000028632 35.299941  0.028328659 0.246649286 Food
  672935819363 26.714539  0.037432801 0.003112476 Nonfood

I want to find out whether the m, p and q of Food products are significantly different from Non-food products. I thought ANOVA would be the best to do that, but when I perform an ANOVA test:
anova(lm(p ~ Food , TotalBassModel1))

I get this output, which does not say anything:
Analysis of Variance Table

Response: p
            Df Sum Sq   Mean Sq F value   Pr(>F)
Food         1 0.0137 0.0137247  10.783 0.001035 **
Residuals 3221 4.0998 0.0012728
---
Signif. codes:  0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1

Who has a suggestion how to do this type of analysis?
Comment: You get a p value of 0.001035, so the output does say something. The real questions are: what are you looking to compare? Average values? Something else? Why? Which is the most appropriate test based on your data and your objectives?
Comment: That p value shows a statistically significant difference in `p` average values between your two `Food` groups. Nothing more, because of the test you've chosen. `p` looks like a continuous variable and `Food` has two groups. Check the `t.test` approach, but also the assumptions involved wit that....
Comment: Besides @AntoniosK comment, you might additionally consider to use logistic regression (or similar) to see how your three variables are simultaneously related to the binary outcome food/non-food.
Comment: Yes, but not what I want to measure. The thing is, I want to see whether people adopt products for food products sooner than for non-food products, for which I needed the p and q parameters of the Bass model. But now, I need to test whether these values are significantly different. Therefore, I thought the ANOVA test would help me, do you have other suggestions? @AntoniosK
Answer: The aov() and lm() functions generate a model object that contains quite a bit of data beyond the F-table for the analysis of variance that was in the original post. Of particular importance are the model coefficients.  Without the coefficients we can't see whether the food or non-food products have a lower coefficient of innovation (the p parameter in the Bass diffusion model). In order to see the coefficients in an ANOVA model, one must save the model object and extract them.
Analysis of Variance is useful when the data conforms to the linear model assumptions, including:

Independence of observations
Normal distribution of dependent variable & residuals
Homogeneity of variances: variance of dependent variable is same across groups

As an example, we will use the Crampton 1947 ToothGrowth data to assess whether supplement type (Orange Juice vs. Vitamin C) lead to different rates of growth in guinea pig odontoblasts, including printing of the model coefficients.
The null hypothesis is that there is no difference in growth of odontoblasts when guinea pigs are given Vitamin C versus Orange Juice. Our alternate hypothesis is that the growth rates are different. We'll set the rejection region for the null hypothesis at alpha = 0.05, meaning that we're willing to take a risk of rejecting the null hypothesis 5% of the time when it is actually true.
Here is the R code required for this analysis:
library(datasets)
data(ToothGrowth)
aModel <- aov(len ~ supp,data=ToothGrowth)
summary(aModel)
aModel$coefficients

...and the output.
> aModel <- aov(len ~ supp,data=ToothGrowth)
> summary(aModel)
            Df Sum Sq Mean Sq F value Pr(>F)
supp         1    205  205.35   3.668 0.0604 .
Residuals   58   3247   55.98
---
Signif. codes:  0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1
> aModel$coefficients
(Intercept)      suppVC
   20.66333    -3.70000
>

How do we interpret the output?
First, the Pr(>F) value of 0.0604 is greater than 0.05, our alpha level. Therefore, we fail to reject the null hypothesis that the supplement type (orange juice vs. vitamin C) leads to larger tooth growth in guinea pigs.
Second, the coefficients tell us that the average growth for guinea pigs given orange juice is 20.6633 microns, and that the impact of giving vitamin C instead of orange juice was -3.70 microns.
Note that in this specific analysis, a second variable, dose explains the effect of supp on len. I cover this in a more detailed article, Commentary of ToothGrowth Factorial ANOVA, where I compare the use of t-test() with aov() referencing an analysis from Robert Kabacoff's R in Action.
Using t.test()
As noted by one of the comments on the original post, t.test() may also be used for this type of analysis, and the output is somewhat easier to interpret than the output from aov().
oj <- ToothGrowth[ToothGrowth$supp =="OJ",1]
vc <- ToothGrowth[ToothGrowth$supp =="VC",1]
t.test(oj,vc,alternative="two.sided",
       conf.level=0.95)

...and the output:
> t.test(oj,vc,alternative="two.sided",
+        conf.level=0.95)

    Welch Two Sample t-test

data:  oj and vc
t = 1.9153, df = 55.309, p-value = 0.06063
alternative hypothesis: true difference in means is not equal to 0
95 percent confidence interval:
 -0.1710156  7.5710156
sample estimates:
mean of x mean of y
 20.66333  16.96333

From the output we see that the oj vector has a mean of 20.66, and the vc vector has a mean of 16.96, or 3.7 less than oj. Since 0 is included in the 95% confidence interval, we fail to reject the null hypothesis that tooth growth in guinea pigs is different when they are given orange juice versus a supplement of vitamin C.


EC2 Tomcat instance with Grails app works VERY differently for multipart upload

Question: I have a grails app that does a simple multipart upload of a file through the following mechanism:
I have a domain object with a transient byte[] field and a multipart form that on submit, goes to a controller that uses request.getFile('name of input form field here').
All this works fine in testing on my local machine, including deploying a war to a tomcat 7 instance on a virtual server that is local.  If I inspect the request in the controller, all is good.
When i put this war up onto a tomcat 7 on an AWS EC2 ubuntu box, everything works fine in the grails app but the file upload.  If I inspect the request (yes, I had intellij hook into the ec2 instance through a firewall hole), the request is a multipart request but has no parts!  No file.  It looks diff than when I inspect it (same code, same intellij setup) locally.
I can find no options in the Amazon tomcat 7 version (yes, they change it some) about what could be doing this.  But my guess is it is either some weird parameter in some config file or some library (I'm going to be diff'ing the libs on the ec2 v. my machines).
Answer: Answer discovered!  In order to combat what I'd thought was the problem, I'd set allowCasualMultipartParsing=true in the Context.
Taking that back OUT, solved the problem.  So, I believe this was the case of a bug in my code originally that I tried a bunch of things to fix, and didn't realize I hadn't backed out all my attempts once I'd found the true source.
So beware that allowCasualMultipartParsing.


what is an easy way to find the asymptotes of the graph $r = \frac1{1+2\cos \theta}?$

Question: i would like to know an easy way to find the asymptotes of the $$r = \frac1{1+2\cos \theta}.$$   this is for a precalculus audience, so it will be nice if calculus can be avoided altogether.
i know that the asymptotes are parallel to the lines $\theta = \pm \pi/3.$  we also know that the $x$-intercepts are $1/3, 1.$
my audience don't know how to use the symmetry, most of them won't even know that the graph is a hyperbola.  can we find the answer without using the symmetry of the graph.
Comment: Well, the function is undefined when $\cos\theta =-\frac{1}{2}$, and, as $\theta$ approaches these, you get the asymptotes.
Comment: @imranfat, we are doing quick sketching of the polar graphs from the graphs of $r$ as a function of $\theta.$ we have done the easy ones $r =1+\sin \theta, \cdots.$  to sketch this graph right, you need more than the direction of the asymptotes.  yes, we can convert it to cartesian and find the asymptotes. but i thought i would ask here and see if anyone has a different idea.
Comment: @ThomasAndrews, the direction of the asymptotes is ok but we need to know one point on each so that we can sketch the graph. i can add this information if that helps.
Comment: You could always convert the polar equation back into Cartesian. It is after all a hyperbola. From there you can easily derive the asymptotes. Cartesian equations of the hyperbola is also Pre-Calculus material I think?
Comment: Ah I see +1. Well, if there is an easy way to find the equations of the asymptotes from the polar equation, I also would like to know...
Answer: Change basis to $\,\vec u_{2\pi/3}$ (the unit vector with polar angle $\frac{2\pi}3$) and the orthogonal vector $\vec v_{2\pi/3}$. An asymptote with polar angle $\frac{2\pi}3$  then has equation $Y=r\sin\bigl(\theta-\frac{2\pi}3\bigr)=l$. Hence you have to determine:
$$\lim_{\theta\to\tfrac{2\pi}3}r(\theta)\sin\Bigl(\theta-\frac{2\pi}3\Bigr). $$
With some trigonometry ($\cos p-\cos q= \dots$), you should find a limit equal to $\frac 1{\sqrt 3}$.
Answer: here is what i came up with. we know that the graph of $r = \frac{1}{1+2\cos \theta}$ as a function of $\theta$ has vertical asymptotes at $\theta = 2\pi/3, 4\pi/3.$
we will show that for $\theta$ near $2\pi /3$ the polar graph is the graph of the slant asymptote of the hyperbola that cuts the $x$-axis at $\frac23.$
let $ \theta = 2\pi/3 + h.$ then
$$\begin{align}
r &= \frac1{1 + 2\cos(2\pi/3+h)}\\
&=\frac1{1+2\left(\cos(2\pi/3)\cos h - \sin(2\pi/3)\sin h \right)} \\
&=-\frac1{\sqrt3\sin h + \cdots} \\
&=-\frac1{\sqrt 3 \sin (t-2\pi/3) + \cdots}\end{align}$$
therefore one of the asymptotes is $$r =-\frac1{\sqrt3\sin (t-2\pi/3)},\, r(0) = \frac23 $$ as claimed.
in the same way we find that the second asymptote is the line
$$r = \frac1{\sqrt3 \sin(t - 4\pi/3)}, \, r(0) = \frac23$$
and we see that the two asymptotes meet at the $x$-intercept $(\frac23, 0).$


Reverse proxy serving html linked content as 404

Question: I've set up this reverse proxy to route a simple web page served on a port (say 61185).
Instead of querying example.net:61185, i'd like to have the same behavior with example.net/listing
Here's the config:
server {
  listen 80;
  server_name example.net;
  location /listing {
    proxy_pass http://127.0.0.1:61185/;
  }
}

The html loads fine, but when fetching the css linked inside it I get a 404.
I noticed the URI is http://example.net/styling.css, how can I make it so that the css is also fetched with the /listing suffix?
Comment: Then add another `location` section to forward `.css` requests.
Comment: I simplified the example, isn't there a way to do that for all linked content in the page?
Ideally I'd like this to be extensible to other more complex pages.
Comment: If you are writing the web app/page, please go to Stack Overflow and learn how to design from day 1 to work with reverse proxy. Then you don't need too many rules.
Answer: The issue you are experiencing is that the URLs for the linked CSS resources in the HTML page are not being rewritten to include the /listing prefix, so the browser is requesting them from the wrong location.
Try this block of code:
server {
  listen 80;
  server_name example.net;
  location /listing {
    proxy_pass http://127.0.0.1:61185/listing;
    proxy_redirect /listing /;
  }
}


OpenGLES fails to generate Framebuffers in iPhone thread

Question: I've got a lovely OpenGLES code slice that renders up images for me. When I want to, I can call a function on it:
<code>-(UIImage *)renderToImage;
</code>
That does a lot of rendering work and returns me an image. This includes the generation of FBOs, textures, etc.
Lately, I've found myself needing to enhance this. The image generation takes four seconds, so I want to pass off the work to another thread and let the app continue. This seemed simple enough. I made a method with this code:
<code>-(void) generateRandomNewImage:(MyViewController *)evc{
UIImage * renderedImage = [self renderToImage];
NSString * fileLoc = [self writeToTempFile:renderedImage];
NSLog(@"File location:%@",fileLoc);
[evc performSelectorOnMainThread:@selector(imageGenerationComplete:) withObject:fileLoc waitUntilDone:NO];
}
</code>
Hopefully you can see the logic going on here. This method renders the image, saves it to the filesystem, and calls a method on the main thread's viewcontroller to let it know the file is ready. This code is inside my opengl renderer. It's called here, in the main thread's viewcontroller:
<code>thread = [[NSThread alloc] initWithTarget:renderer
                           selector:@selector(generateRandomNewImage:)
                           object:self];
[thread start];
</code>
To me, that seems fine too. When I run this code, I get told in my console that my framebuffer object status were error'ed, with a status of zero. I have no idea why. As a result, I get a blank image (saving to the temp files work, by the way, I've tested them).
To test, I put all of this code into the main thread, didn't create any new threads or anything. It all worked fine. As soon as I try and pass off the image generation to another thread, I hit problems.
Answer: Using OpenGL in another thread is not that simple as that, only one thread can use a OpenGL context at a time, and your second thread doesn't have a OpenGL context, thus all OpenGL calls fail.
Solution: Create another OpenGL context for the second thread, and read this.
Comment: Read also this: http://stackoverflow.com/questions/1253145/how-to-use-opengl-es-on-a-separate-thread-on-iphone if you're considering sharing state between the contexts.
Comment: Awesome. This is precisely what I needed/


Como passa dados para uma Classe php via ajax sendo que está classe instancia outra?

Question: Ola pessoal espero que possam me ajuda, estou com esse problema a muito tempo
Eu passo meu dados via Ajax para minha classe mas na URL não sei como faço para alcança-la de uma forma que não de erro
eu tentei da seguinte forma
$.ajax({
     type:'post',
     url:'Classes/Usuario.class.php',
     ajax:'1',
     data:{id:1},
     success: function (data){
          alert(data)
     }
});

Bom, observações caso ajude a me responderem.
É Obviou que vai dar erro kkkk, como disse minha classe Usuario instancia outra, estende outra então não consigo passar meus valores assim.
Outra coisa que pode ajudar, minhas classes são chamadas automaticamente pelo método magico __autoload(). Eu creio que dessa forma exista uma maneira diferente para escrever a URL.
Bom pessoal, por favor nao indiquem outro post, caso nao entendam diga nos comentarios que estarem com vcs até conseguirmos resolver este problema !
Obrigado por estarem me ajudando ! Até..
Como solicitado estou logo abaixo vem o código do arquivo Usuario.class.php
<?php
/**
 * Created by PhpStorm.
 * User: Pedro
 * Date: 19/01/2016
 * Time: 00:43
 */

class Usuario extends BancoPizza
{
    public $Tabela = 'pizzaria';
    public $Campos = array(
        'nome_pizzaria',
        'usuario_pizzaria',
        'senha_pizzaria',
        'rua_pizzaria',
        'numero_pizzaria',
        'bairro_pizzaria',
        'cidade_pizzaria',
        'uf_pizzaria',
        'status_pizzaria'
    );

    /**
     * @param $dados -> Campos da tabela
     * @param $Campos -> A classe ja tem os campos da tabela
     */

    public function verUm($where=null){
        return parent::verUm($this->Tabela, $where);
    }

    public function verTodos($where=null, $ordem=null)
    {
        return parent::verTodos($this->Tabela, $where, $ordem);
    }

    public function excluir($where)
    {
        //Aqui eu queria pegar a Id do item clicado e através do ajax passar essa id, porem preciso saber como especificar o método que esse meu valor vai, correto ?
        return $_POST['id'];
        return parent::excluir($this->Tabela, $where);
    }

    public function editar($campoTabela, $valor, $id)
    {
        parent::editar($this->Tabela, $campoTabela, $valor, $id);
    }
}

Comment: A classe não deixa de ser um arquivo logo é so pegar o post e passar os valores para o objeto
Comment: poste o código da sua Usuario.class.php. O código acima deve ir para algum método na classe Usuario correto? Qual?
Comment: @ThomasLima - cara vc disse uma coisa muito improtante, especificar o método que meus valores vão, a cima atualizei o código. Ficou mais claro para me ajudar ?
Comment: @PedroSoares aparentemente seu único problema é falta de informar para qual método você quer enviar seus dados. Você está usando MVC?
O ideal é que você envie seus dados para uma classe controle, ela será responsável por instanciar sua classe usuário e chamar o método correspondente.
Comment: Não mande o post direto para o arquivo da classe!Envie para uma outra página php que inclua as classes necessárias, instancie elas e faça todo o processo necessário.
Comment: @ThomasLima Acho que estou pegando a ideia, você pode me explicar como faço para chamar o método a partir da URL ?
Comment: @PedroErick - Vou tentar isso, mas o Thomas tem razão, preciso chamar o método além de chamar a classe e instancia-la .. mas não sei como faço isso
Answer: Parceiro, partindo do pressuposto de que você não está utilizando MVC, sugiro algo assim:
$("body").delegate(".btnAcao", function(e){
     e.preventDefault() //Retirando o comportamento padrão

/*
     *Você pode recuperar os valores do seu form utilizando o método .serializeArray()
     */
    var arrayDados = $("#id_do_form").serializeArray();
    arrayDados['funcao'] = 'excluir';

    $.ajax({
         type:'post',
         url:'Classes/usuario-controller.class.php',
         data: arrayDados,
         success: function (data){
              alert(data)
         }
    });

});

Ao invés de chamar diretamente a sua classe Usuário, você envia seus dados para uma outra página que será responsável por fazer essa ligação entre a sua exibição (View) e a sua classe Usuário (Model). Chamei esse novo arquivo de usuario-controller.php.
Note que os valores do meu form foram pegos com o .serializeArray()
usuario-controller.php
<?php

/**
 * adiciona todos os seus includes que você precisa...
 *
 * Nesse momento você pode recuperar os valores do seu form normalmente.
 * Aqui você também poderá tratar suas variáveis, limpando-as e se certificando de
 * que os dados que foram inseridos estão corretos
 */
$id = filter_input(INPUT_POST, 'id');
$nome = filter_input(INPUT_POST, 'nome');
$email = filter_input(INPUT_POST, 'email');
$telefone = filter_input(INPUT_POST, 'telefone');

$metodo = filter_input(INPUT_POST, 'funcao');

//Instancia a classe que precisa
$usuario = new Usuario();

/**
 * A partir desse momento você poderá chamar o método que você deseja.
 *
 * OBS: Lembrando que o seu retorno para o página anterior virá daqui...
 *
 * Como exemplo, vamos excluir o registro informado:
 */

echo $usuario->$metodo($id);

//Se tudo ocorrer bem, o seu retorno será true.

A lógica é essa, basta adaptar para o que você precisa.
Espero ter ajudado!
Comment: nao é possivel fazer isso por dentro da minha classe eu tenho funções, e nao sei como faço para a função certa receber o valor passado pelo ajax.. alguma ideia ?
Comment: @PedroSoares o correto é que o arquivo usuario-controller.php receba os dados, crie a instância de Usuario e manipule suas funções. Você pode criar um outro parâmetro no ajax chamado funcao por exemplo, ai lá vc passa o nome do método que deseja chamar. Veja resposta editada. Você até pode fazer isso direto na classe Usuario, mas terá que fazer essa lógica de receber os dados e instanciar a classe fora da definição da classe, ou seja, fora do { ... }
Comment: sim sim, CARA É DISSO QUE EU PRECISO. finalmente, pode me mostrar um exemplo ?


How to revise forecast in middle of the period as per actualized demand

Question: I am making monthly forecast of sales volume, and have IT system in place to observe daily sales. I want to compare actual sales with forecasted sales every 10 days (twice in a month - on 10th and 20th day of every month), and then adjust previously forecasted value for the month if required. Idea is that actual sales volume for first 10 days should help in improving/adjusting forecast for remaining 20 days. A Naive approach will be to look at the ratio of actual vs forecasted sales for first 10 days and then use this ratio to adjust forecast for remaining 20 days. Is there any statistical methodology to do it in better way? Any pointer will be helpful? Please note that actual sales is not uniform across 10 days bucket, I observe that sales generally pick up in last 10 days of the month.
Example : Suppose forecast for December 2017 is 300 units (that will be 10 units per day assuming uniform distribution of demand). On December 10th, total sales till date comes to be 120 units, question is that how can we revise forecast for remaining 20 days?
Note : I have historical sales data available for last 3 years, and monthly forecast is time series forecast using this historical data. In general sales follow seasonal trend.
Comment: Why not use all available information at all times to obtain the best forecast?
Answer: Your proposed approach is ad hoc, but it makes sense.
One question is whether higher sales during the first 10 days of a month actually predict higher sales during the rest of the month ("short term trend"). After all, it might well be possible that customers who were going to buy during the second half of the month decided to pull their purchase forward in time - and in this situation, higher sales at the beginning of the month might actually predict lower sales during the rest of the month.
Many customers of ours want forecasts to be "highly reactive" in the way you are describing. It usually leads to higher volatility and lower accuracy. I strongly recommend that whatever you do, you examine carefully whether your "high adaptivity" makes matters better or actually worse.
The alternative would be to directly model and forecast on daily granularity. If you have multiple-seasonalities (intra-yearly and intra-monthly, with higher sales during the last third of a month), you can use appropriate models like bats or tbats.
Comment: Thanks Stephan!  Customers preponing their purchase from second half to first half of the month is not much concern for now (it should be taken care when we aggregate at month level). Problem comes when there is level shift because of some recent development. For ex, if a competitor reduces its price then our sales is likely to go down, and these recent developments are not included in time series forecast. Assumption is that last 10 days of sales should give us signal if there is level shift. I am starting with ad hoc methodology, comparing previous forecast with revised (as you suggest).


como enviar dados para outra pagina em html

Question: eu tenho um formulario em que o usuario vai preencher com os dados e irá voltar para a pagina inicial do site, e uma tela de login do adm em que ele ira logar e ira ver uma pagina com os dados que os usuarios preencheram, como faço isso?

agora quero direcionar o usuario ao index.html e o ADMform a essa pagina recebendo os dados que o php ta imprimindo
Comment: Coloca esse trecho de codigo na pergunta, fica mais fácil de compreender
Answer: Sua pergunta está confusa, mas se entendi bem, você quer ter acesso à informações de todos os usuários que preencheram estas informações. Se for isso, você precisa de um banco de dados para armazenar estes dados e poder consulta-los depois.
Um exemplo com MySQL seria:
$server = "localhost";
$user = "root";
$password = "";
$dbname = "nomeDoBanco";

//Criar a conexao
$con = mysqli_connect($server, $user, $password, $dbname);

Depois disso, você precisa de uma query para cadastrar infos:
mysqli_query($con,"INSERT INTO nomeTabela (campos) VALUES $info1, $info2..." ):

E para exibir todas para o administrador:
mysqli_query($con,"SELECT * FROM nomeTabela");

Caso não seja isso que você quer, explique melhor a sua dúvida. Se não faz ideia do que estou falando, pesquise um pouco sobre Banco de Dados.
Obs. para direcionamento de páginas você pode usar:
echo "";


How to assign full processor(cores/sockets) to a VM? VMware

Question: Trying to use VMware. Using Ryzen 9 5950X(16 cores / 32 threads).
The question is how to assign all cores/threads properly to a VM? Were trying different configurations of "Number of Processors" along with "Number of cores per processor". Like 2/16, 16 / 2, 8 / 4 and so on but never got proper value.
Wanna push all, so could use the whole power of CPU in VM :), or at least most.
OC: Windows 10
P.S When I was assing 16 / 1, then in VM i see 2 sockets with 2(or 4) cores via task manager
Thank you for the help!
Answer: If you want to push the whole processor, use the following config:

Number of processors: 1
Number of cores per processor: 32

But be aware that, unless you have another processor, it may crash or give you slow performance, since you need some processing power for the main OS. I would recommend using 24-26 cores per processor instead.
Answer: VmWare is type 2 hypervisor, which run runs on the host operating system. Type 2 hypervisors can support the maximum of 75% of host hardware. Those hypervisors are type 2 hypervisors: "VmWare, Virtualbox, Parallels, Qemu, ..
Meanwhile type 1 hypervisors, such as "Hyper-v, Microsoft Virtual pc, Windows Sandbox, .. run on the host hardware, so they can use much more hardware than type2 h-vs. So if you plan to use full power of your cpu, i do reccomend using type1 hypervisors, but they have a few disadvantages, such as they rather support Windows Server guest operating systems, and they don't have that much features, such as build in direct vnc connection.
Hope this helped.


Reference for known issues with histograms (binning, anchor point)

Question: I'm looking for references on the known issues that arise when working with histograms, i.e.: the choice of the number of bins, and the choice of the origin point.
The WP entry on Multivariate kernel density estimation points to Density Estimation for Statistics and Data Analysis, Bernard. W. Silverman (1986).
This book comments briefly on these issue in Sect. 2.2 (see below). Is there some other "canonical" reference for this topic or should this one suffice?

Pages 10-11 from Silverman (1986). Copyrighted material.
Comment: I get "Restricted Page - You have reached your viewing limit for this book". What did it say? Please include a quote of the most relevant parts
Comment: Must be some country restriction. I am not allowed to copy/paste text in the book since it's disabled. I'll paste some images from the relevant pages.
Comment: If it's only a few sentences, simply type it in as a quote.
Comment: @Glen_b should I remove the images from the pages I posted?
Comment: For the sake of completeness, this great answer by Glen mentions such issues http://stats.stackexchange.com/a/51753/10416, but no book or article to serve as reference is given.
Comment: Yep, there's no references there because I invented the examples. That's not to say I invented the concept that this happens, and I had definitely read something written by someone else talking about it before, but I couldn't find where that was when I posted that earlier post (and I still can't - I just attempted to find it) -- but I have posted some references that I just found now.
Answer: I decided to go looking for a particular paper that I saw briefly, probably at least a decade ago, since it would be relevant (to my recollection it discusses issues with the impact of bin width on the impression of shape with a striking example that looks sort of exponential at one bin width and not exponential with another) but I couldn't find it. In searching for it, I did come across a few things though, including:

Jeffrey S. Simonoff (1996) Smoothing Methods in Statistics
Sec 2.4 (in particular p28 and 29 including figure 2.8 discusses the
effect of changing bin anchor
Also see
Simonoff, J. S. and Udina, F. (1997),
"Measuring the stability of histogram appearance when the anchor position is changed",
Computational Statistics and Data Analysis, 23, (1997), pp. 335-353,
http://hdl.handle.net/10230/655
Besides discussing bin anchor (bin origin), it also looks to have at least some discussion of bin width; fairly technical. Figure 1 in that papershows the impact of changing bin origin on a data example
The 2004 book by Härdle, Müller, Sperlich, and Werwatz,
Nonparametric and Semiparametric Models discusses the effect of bin origin - Figure 2.3 shows an example of the effect of changing binwidth and section 2.3 discusses the effect of changing bin origin.
Härdle, W., Müller, M., Sperlich, S., & Werwatz, A. (2004).
Nonparametric and Semiparametric Models.
New York: Springer Series in Statistics, Springer
and closely related to that,
Marlene Müller (2010),
"Exploring data with non- and semiparametric models."
ICOTS8 Invited paper,
http://iase-web.org/documents/papers/icots8/ICOTS8_4B3_MULLER.pdf
also has a similar brief discussion and figure 1 shows the effect in an example
Keith N. Sircombe (2004),
"AgeDisplay: an EXCEL workbook to evaluate and display univariate geochronological data using binned frequency histograms and probability density distributions",
Computers & Geosciences 30, 21–31
shows an effect on the appearance of histograms of changing bin width:

The subtle variation in appearance and interpretation for a variety of  bin widths is illustrated in Fig. 3. Although all the histograms show the age distribution is generally dispersive with two prominent modes (~2950 and ~3150 Ma), the relative prominence of the two modes change; this could alter interpretations about the relative importance of these modes.

David C. LeBlanc (2004), Statistics: Concepts and Applications for Science, Vol. 2
Figure 2.3 (Sec 2.2, p39) shows the effect on appearance of changing bin width on a histogram
Comment: Excellent list of resources Glen, thank you very much!


Well-orderings of $\mathbb R$ without Choice

Question: The question is about well-ordering $\mathbb R$ in ZF. Without the Axiom of Choice (AC) there exists a set that is not well-ordered. This could occur two ways: a) there are models of ZF in which $\mathbb R$ is well ordered and some other set isn't; or b) there are models in which $\mathbb R$ itself can not be well-ordered. Both possibilities are consistent with ZF.
Do I have this right?
If so then I am confused about the following argument that $\mathbb R$ must be well-ordered even in the absence of choice.
Let $\mathfrak c$ be the cardinality of $\mathbb R$. It's easy to show that $\mathfrak c = 2^{\aleph_0}$.
Now (this is the part that's got me confused) in set theory cardinals are defined as certain ordinals. Therefore $\mathfrak c$ is some ordinal; which immediately induces a well-order on $\mathbb R$.
What is wrong with this argument? I can imagine a couple of scenarios but without much confidence.

$\mathfrak c$ is a cardinal but it is possible that it's not well-ordered. But if it's a cardinal that's not an ordinal, then what is it? This scenario seems unlikely.
Or perhaps $\mathfrak c$ is not always well-defined. When people say, "Let $\mathfrak c$ be the cardinality of $\mathbb R$," they typically neglect to prove that such a thing exists. Perhaps there are models of ZF in which $\mathbb R$ has no well-defined cardinality at all. This seems like the only sensible way out, in which case there are a lot of misleading expositions out there.

I found several Stackexchange questions about properties of well-orderings of $\mathbb R$ under AC; but nothing about this particular question. According to this article the reals might not be well-ordered in Solovay's model in which all sets of reals are Lebesgue-measurable; but this requires an inaccessible cardinal. What happens if we take the inaccessible away?
In general what is the correct way to understand well-ordering the reals in ZF?
Comment: When I move from a cellphone to a better equipped computer, I will find the duplicate of this question.
Comment: In the meantime, for your consideration: http://math.stackexchange.com/q/53770/622 http://math.stackexchange.com/q/172316/622 http://math.stackexchange.com/q/258510/622 http://math.stackexchange.com/q/53752/622 http://math.stackexchange.com/q/228036/622 and that last one is particularly relevant to your question.
Comment: @AsafKaragila Thank you for the references, very helpful.
Comment: I am replying to your comment on a just deleted post, and I agree with you the hard edge should be softened. I also agree that teachers are not doing a good job.
Answer: Tl;dr: the cardinality of a set need not be a cardinal. Yes, this is terrible terminology.
The former possibility is what happens if $\mathbb{R}$ is not well-orderable. $\mathfrak{c}$ is always well-defined; it's just that, in the absence of choice, it need not be an ordinal.

Note that this means that we need to be careful with our terminology when working in just $ZF$: we need to distinguish between cardinals in the sense of initial ordinals (equivalently, cardinalities of well-orderable sets) and cardinalities in general.
For that matter, we need to be a little careful how we define a possibly-non-well-orderable cardinality! We use the notion of rank. The rank of a set is defined in terms of the cumulative hierarchy. We define $V_\theta$, for every ordinal $\theta$, inductively as follows:

$V_0=\emptyset$,
$V_\lambda=\bigcup_{\beta<\lambda} V_\beta$ for $\lambda$ limit, and
$V_{\alpha+1}=\mathcal{P}(V_\alpha)$.

Then by the Axiom of Foundation, we can show that for all $A$ there is some $\theta$ such that $A\in V_\theta$. The least such $\theta$ is the rank of $A$. Moreover, each $V_\theta$ is a set.

If $X$ is a non-well-orderable set, then we let $\vert X\vert$ be the set of all sets $Y$ such that $(i)$ $Y$ is in bijection with $X$, and $(ii)$ the rank of $Y$ is as small as possible (no set of strictly smaller rank is in bijection with $X$).

That is, we take a Fregean approach - a cardinality is a set of all sets of a given size - but use the notion of rank to make the result a set, instead of a proper class (this is called Scott's trick).
Note that, however, this clashes slightly with the definition of the cardinality of a well-orderable set; but this doesn't really cause any problems.

By the way, I think Solovay's model is a bit of a red herring, here. The most straightforward way to break the well-orderability of $\mathbb{R}$ is Cohen's original model; Jech's big book has a good exposition of it. This does require forcing, though, so is a serious chunk of work to get through.
Comment: And if we throw out Choice *and* Foundation, then we just can't have cardinals as sets? How much should we care? If cardinal numbers are proper classes, does that cause any problems for "working" mathematicians and "naive" set theoreticians, or is it only a concern for advanced work in set theory?
Comment: @bof If we throw out Choice and Foundation, then it is *possible* that we won't have cardinals as sets in any nice way; if I recall correctly, this was addressed in a Mathoverflow question a long time ago (EDIT: it was http://math.stackexchange.com/questions/305859/scotts-trick-without-the-axiom-of-regularity, which also kills extensionality a teensy bit via atoms but that's a small price to pay; see also http://www.ams.org/mathscinet-getitem?mr=366666). However, we can still express e.g. equinumerosity, so almost nothing changes.
Comment: Very clear, thanks much.
Comment: I still think this leaves part of the original question unanswered: Can we prove in ZF that $\mathfrak c=2^{\aleph_0}$? If so, doesn't that imply that $\mathbb R$ must be well ordered in ZF, since it can be put into bijection with an ordinal?
Comment: @WillG Yes, $\mathfrak{c}=2^{\aleph_0}$ is provable in ZF - in fact, that's almost the **definition** of $\mathfrak{c}$. However, $2^{\aleph_0}$ need not be an ordinal in ZF alone! It may help at this point to look back at the definition of $2^{\aleph_0}$. It's defined as "the cardinality of $\mathcal{P}(\omega)$." But when we're working in ZF, cardinalit**ies** need not cardinals, that's the whole point of my answer. So in fact there's no tension here (or incompleteness in the answer).
Comment: @NoahSchweber Aha, thanks. I am reading Jech, and his Lemma 3.3 reads "If $|A|=\kappa$, then $|P(A)|=2^\kappa$. If we let $\kappa=\omega$, then this reads "If $|\omega|=\omega$, then $|P(\omega)|=2^\omega$." Doesn't this imply that $2^{\aleph_0}=|P(\omega)|$? Maybe the issue is that $P(\omega)$ isn't necessarily an ordinal in ZF?
Comment: @WillG The point is exactly that **none** of these things are ordinals in ZF alone (really, they're all more-or-less the same object - depending on the specific definitions used, the equalities between them are either very easy or literally trivial to prove - so the non-ordinalness is the only nontrivial fact here). Again, the whole point is that when we're in ZF alone, **cardinalities need not be cardinals** (more concretely, despite our ZFC-instincts expressions like "$\kappa^\lambda$" or "$\vert X\vert$" need not correspond to well-orderable objects in ZF alone).
Comment: Ok got it. It's just that in Jech's book, he only defines $|X|$ for well-ordered sets $X$ and omits any definition of "pre-choice" general cardinalities. I was reading his Lemma 3.3 as implying that $|P(A)|$ makes sense under his definition if $|A|$ does, but I guess that isn't true?
Comment: @WillG Since ZFC is the context of that book, that lemma is proved within ZFC, and so there's no reason to expect it to be still provable exactly as stated in a weaker theory like ZF. An **analogue** of that lemma holds (again, basically trivially) in ZF, but involves changing the definition of $\vert\cdot\vert$. Again, the whole point of my answer is that when we go to ZF we have to change the very definition of cardinality in order for cardinality to work properly (e.g. for $\vert \mathcal{P}(\omega)\vert$ to actually mean something).
Answer: According to the Wikipedia article Cardinal number, in ZFC, the cardinality of any set is defined to be the smallest ordinal number that is equivalent to that set, that is, there is a bijection from that ordinal number to that set. That's probably because in ZFC, it can be proven that for all sets, there is a smallest ordinal number that is equivalent to that set. The problem with your proof that the set of all real numbers can be well ordered is that you need the axiom of choice to prove that the cardinality of all sets can be defined in that way and therefore that $\mathfrak c$ is an ordinal number according to that definition.


Creating a Field in order to add Icons to content's Title

Question: we want to add Icons before the Content's title just like the picture below (icon before Glory of the Hero):

but the problem about the stuff already existing in prior asked questions is that we're gonna work with that a lot in our site , so if we're gonna code it for EACH title, it wouldn't be useful for us >>>>> so we wan to add a field in our content types for example called title's image , and so each time we upload a file there, we'll have an icon before that content's title.
I've already read:

Icon images with node title
https://www.drupal.org/node/140517
https://stackoverflow.com/questions/8976315/drupal-7-display-images-instead-of-nodes-titles
https://stackoverflow.com/questions/10665893/how-to-add-image-with-title-of-an-html-page
Optionally add image/icon after node title based on boolean content type field?
https://www.drupal.org/node/270332

and they didn't help at all...
is there any way to do that?
Answer: You can do this by creating node.tpl file.
    <?php print render($title_prefix); ?>
      <?php if (!$page): ?>
     //"print image here"
 <h2<?php print $title_attributes; ?>><a href="<?php print $node_url; ?>"><?php print $title; ?>

      <?php endif; ?>
      <?php print render($title_suffix); ?>

You can get all the field value here and just print the image before the title.
Answer: I think I have a solution for you, a bit tricky though. Do the following

Install/enable "devel" module
Override page.tpl.php to page--node--%.tpl.php (or you could use the page.tpl.php)
Find the title element in the page.tpl.php , looks like following

Make sure that you have a field called icon (note the machine name i.e. field_icon) in your content type
Create a sample of your content type
Click on "Devel" tab and try to find the field_icon or whatever you named the field, as shown in the following screenshots

and clicking on the field_icon, you will see a structure similiar to this

Just before the h1 tag, in the screenshot of page.tpl.php shown in #3 add a code that looks like the following:
<img src="<?php
        $var = $page['content']['system_main']['nodes'];
        $element;
        foreach($var as $k => $v) {
        $element = $v ;
        #obtain the node id, usually first.
        break;
        }
        #$exist = $element[$element['field_icon']['#object']->field_icon['und'][0]['uri'];
        if(isset($element['field_icon'])) {
        print $element['field_icon']['#object']->field_icon['und'][0]['uri'];
        } else {
        #does not exist
        }
    ?> " />

The code above creates an image tag, and its src value would be the value of the URI of the icon. Use Devel (or kpr($page['content']['system_main']['nodes']); inside page.tpl.php) tab to figure out what to replace with $page['content']['system_main']['nodes'], probably it might remain the same for you as well.
Once you got the content of the $page['content']['system_main']['nodes'] or similar then loop through it to find the node-id (which can be anything). The reason I have a break in loop is because, I am interested in first element which is node-id, see below

And finally access the URI as shown in the following Devel Screenshot

Nothing will be printed in pages where there is no field_icon (i.e. icon machine name), and the icon should be printed in pages that have that field in its $page variable. Good luck.
Here is the result:


angles in rhombus when an equilateral triangle is inscribed in it

Question: When one inscribs an equilateral triangle in a rhombus, all the corners are multiples of 30 degrees. I can see this, but I can't proof it.
Question: How can I proof that the angle ADC is 120 degrees?

And how do I claim that the triangle SHB (S being the intersection of the diagonals) is similar with triangle FHC? I can see it and I think there is an easy way with parallel lines (why is EF || AC) and bisectors (the diagonals of a rhombus) but I just can not put my finger on it...
Any help and/or hints are really appreciated.
Comment: This isn't true. You can inscribe an equilateral triangle in a square, which clearly doesn't have any $120^\circ$ angle.
Comment: Perhaps there are some assumptions in the problem setup that you have unintentionally omitted?  A rhombus can be of varied aspects, not just the back-to-back equilateral triangles you seem to illustrate.
Answer: The angle aren't multiples of 30 degree. It can be any value you like. If $D$ is moved upwards  then $A$ and $C$ contract inwards (and move upwards as well) and vice versa.
Some examples:
Answer: It is incorrect. Rhombuses of varying aspect ratio are possible to be circumscribed through $DAC$ with a variable height $BD$.


R finding list member with the smallest RSS

Question: I wrote a function that uses the loop below, intending to find starting values for a nonlinear regression. I wonder if there is a procedure to scan the whole list that results from the loop, and find the parameter set that produces the smallest RSS.
for (c1 in seq(0.95*min(trans), 0.95*max(trans), mean(trans)/10)){
for (gamma in seq(1,100,1))  {

  lin_eq     <- paste0("lag_0 ~",  paste(paste(colnames(linear_dat)[-1]), sep="",collapse='+'))
  nonlin_eq  <- paste0("transition + ",paste("I(transition*",paste(colnames(nonlinear_dat),")"), sep="",collapse='+'))

  transition <- (1+exp(-(gamma/scale)*(trans-c1)))^-1

  grid.regre <-lm(paste0(lin_eq,"+",nonlin_eq),data=data.frame(linear_dat,nonlinear_dat,trans))

  coef <- grid.regre$coefficients
  RSS  <- sum(grid.regre$residuals^2)
  grid[[length(grid)+1]] <- c(RSS,gamma,c1,coef)
}

}
Thanks a million.
Answer: num <- which.min( sapply(grid, "[[", 1) )  # the item number with min RSS
grid[[num]] # the whole list entry

Comment: I replaced "RSS" by 1, trying to extract the first element of every member in the list. It works perfectly. Thank you!
Comment: Oh, you're right. I did not notice that you you had not named the list elements.