Calculate definite integral $\int^b_a e^{-x^a}dx $

Question: Is there any closed form expression for $\int^b_a e^{-x^k}dx$ ?. With $z=x^k$, we have
$\int^{b^k}_{a^k} 1/k e^{-z} z^{1/k-1} dz$. Then I have no idea what to do next. It appears I have a gamma function. Any suggestion will be appreciated!
Comment: no closed form for such expresion exists except for a=0 and b=infinity
Answer: There is no closed form solution except for a special case, as has been articulated in a comment. In case you are interested here it is:
\begin{align}
\int_0^{\infty} e^{-x^\alpha}\,dx=\Gamma\left(1+\frac{1}{\alpha}\right)
\end{align}
EDIT:
Yes, this integral can be expressed in terms of the incomplete Gamma functions  $\Gamma(n,x)$ and $\gamma(n,x)$.
\begin{align}
I&=\int_a^b e^{-x^k}\,dx \qquad u=x^k\\
I&=\frac{1}{k}\int_{a^k}^{b^k} u^{\frac{1}{k}-1} e^{-u}\,du\\
I&=\Gamma\left(1+\frac{1}{k}\right)-\frac{1}{k}\,\gamma\left(\frac{1}{k},a^k\right)-\frac{1}{k}\,\Gamma\left(\frac{1}{k},b^k\right)
\end{align}
This can even be simplified:
\begin{align}
\int_a^b e^{-x^k}\,dx=\frac{1}{k}\,\Gamma\left(\frac{1}{k},a^k\right)-\frac{1}{k}\,\Gamma\left(\frac{1}{k},b^k\right)
\end{align}
Comment: Is it even possible to write it in terms of some incomplete gamma functions?


Android.mk conditions

Question: Is there any way to use conditional expressions in Android.mk? I need it to do smth like this:
IF arch = AREABI_V7
   *use path for my arm_v7 static libs*
ELSE
   *use path for arm static libs*

Answer: ifeq ($(TARGET_ARCH_ABI),armeabi-v7a)
    ...
else
    ifeq($(TARGET_ARCH_ABI),armeabi)
        ...
    endif
endif

Comment: You have missing space after second `ifeq` before the `(`. The build system errors on that.
Comment: "The NDK docs state that Android.mk "is really a tiny GNU Makefile fragment...".
Here are the docs about make conditionals:
http://www.gnu.org/software/make/manual/html_node/Conditionals.html " //Taken from here https://groups.google.com/forum/#!topic/android-ndk/UCqQ1L2kisE

Android.mk conditions


A binomial inequality

Question: I've tried both expanding the binomials as well as trying to deduce something from the hypergeometric distribution, but I don't see how to prove:
$${N\choose n}^{-1}\sum_{i\geq j}{M\choose i}{N-M\choose n-i}{i\choose j}\leq {n\choose j}\left(\frac{M}{N}\right)^j.$$
Answer: Using the factorial formulas for binomial coefficients and Vandermonde's Identity, assuming $M\le N$, we get
$$
\begin{align}
\hspace{-1cm}\binom{N}{n}^{-1}\sum_{i=j}^n\binom{M}{i}\binom{N-M}{n-i}\binom{i}{j}
&=\binom{N}{n}^{-1}\sum_{i=j}^n\binom{M}{j}\binom{N-M}{n-i}\binom{M-j}{i-j}\tag{1}\\
&=\binom{N}{n}^{-1}\binom{M}{j}\binom{N-j}{n-j}\tag{2}\\
&=\binom{M}{j}\binom{N}{j}^{-1}\binom{n}{j}\tag{3}\\
&\le\left(\frac MN\right)^j\binom{n}{j}\tag{4}
\end{align}
$$
Explanation:
$(1)$: $\binom{M}{i}\binom{i}{j}
=\frac{M!}{i!\,(M-i)!}\frac{i!}{j!\,(i-j)!}
=\frac{M!}{j!\,(M-j)!}\frac{(M-j)!}{(M-i)!\,(i-j)!}
=\binom{M}{j}\binom{M-j}{i-j}$
$(2)$: Vandermonde $\implies\sum\limits_{i=j}^n\binom{N-M}{n-i}\binom{M-j}{i-j}=\binom{N-j}{n-j}$
$(3)$: $\binom{N}{n}^{-1}\binom{N-j}{n-j}=\frac{n!\,(N-n)!}{N!}\frac{(N-j)!}{(N-n)!\,(n-j)!}=\frac{n!}{j!\,(n-j)!}\frac{j!\,(N-j)!}{N!}=\binom{N}{j}^{-1}\binom{n}{j}$
$(4)$: $M\le N\implies\frac{M}{N}\frac{M-1}{N-1}\frac{M-2}{N-2}\cdots\frac{M-j+1}{N-j+1}\le\left(\frac MN\right)^j$

A binomial inequality


Update with Join in SQLite

Question: I have 2 tables and like to update one of them with the values from the other.
software
---------
id ,
purchprice

softwarecost
------------
id ,
purchprice

I've tried these queries but, SQLite doesn't support JOINS with UPDATE.anybody out there who can come up with  a query for this.thanks for your help.
UPDATE software
SET software.purchprice=softwarecost.purchprice
WHERE software.id=softwarecost.id

UPDATE software
INNER JOIN softwarecost on software.id=softwarecost.id
SET software.purchprice=softwarecost.purchprice

Comment: Of course sqlite supports joins.
Comment: Related for DELETE: https://stackoverflow.com/questions/24511153/how-delete-table-inner-join-with-other-table-in-sqlite
Answer: This will work
UPDATE
      software
SET purchprice = (SELECT purchprice
                  FROM softwarecost
                  WHERE id = software.id)
where EXISTS (SELECT purchprice
                  FROM softwarecost
                  WHERE id = software.id)

Here we use exists because
without that the query will set software.purchprice to null if no "correlated" row is found.
Comment: Since v3.33 (release 14th August 2020) sqlite supports an UPDATE FROM syntax: https://www.sqlite.org/lang_update.html#upfrom
Answer: You have to look up the corresponding values with a correlated subquery:
UPDATE software
SET purchprice = (SELECT purchprice
                  FROM softwarecost
                  WHERE id = software.id)

Comment: I just tried this. the field purchprice in entire table software will have the same value. it doesn't do a join.
Comment: But beware that this will set `software.purchprice` to `null` where no "correlated" row can be found in `softwarecost`.
Comment: @Colin'tHart That seems like the desired behavior, no?
Comment: SQLite3 doesn't seem to support `WHERE`statements referring to other tables in the db (I am running a similar code to above and get the error `Error: no such column: software.id`). Any clues or should I open a new  question?
Comment: @lmrta You can refer only to tables used by the UPDATE or by a SELECT.
Answer: Using the new UPDATE FROM syntax, which was introduced in v3.33 (release 14th August 2020) as suggested by Pelle Jacobs in a comment.
UPDATE software
SET purchprice = c.purchprice
FROM (SELECT purchprice, id FROM softwarecost) AS c
WHERE c.id = software.id;

Comment: Note that "update from" is supported since version 3.33
Answer: This statement will work fine!
It will update only rows in 'software' that have the same ID in 'softwarecost'!
UPDATE software SET software.purchprice =
     (SELECT purchprice FROM softwerecost WHERE software.id = softwerecost.id)
     WHERE id IN (SELECT id FROM softwarecost);

One more way to do it:
DELETE FROM software WHERE id IN (SELECT id FROM softwarecost);
INSERT INTO software SELECT * FROM softwarecost;

...this way is more convenient if you have to update all columns (if you have more columns to update)
Answer: I just found this one, using an UPSERT:
INSERT INTO software (id, purchprice)
SELECT a.id, b.purchprice FROM software AS a INNER JOIN softwarecost AS b ON a.id=b.id
ON CONFLICT(id) DO UPDATE SET purchprice=excluded.purchprice

This only works if you have

SQLite version 3.24.0 or above and
a UNIQUE constraint on software.id, e.g. by defining it as primary key.

It does not need potentially slow correlated subqueries and can handle multiple column updates.
Comment: It is a reserved pseudo-table, which is automatically made available by the UPSERT syntax.
See the linked SQLite doc:
"Column names in the expressions of a DO UPDATE refer to the original unchanged value of the column, before the attempted INSERT. To use the value that would have been inserted had the constraint not failed, add the special "excluded." table qualifier to the column name."
Comment: Where do you get "excluded." from?
Comment: Thank you. It worked for me as a replacement for UPDATE FROM on SQLite 3.27.2 (as UPDATE FROM is available only since 3.33).
Answer: The other answers here are mostly correct but one slight change is needed.  At least I certainly needed to make a change for it to work.  Not sure if it was a change to SQLite that's occurred over the years or just that it was never caught here, but you need to fully qualify the reference to column id from softwarecost within the WHERE clause to be WHERE softwarecost.id = software.id instead of just WHERE id = software.id.  Without doing this the query I just ran made all entries the same value and it was the first value that linked - meaning all entries of software.purchprice became the same as the first entry in softwarecost.purchprice.  This, I presume, is due to the id column being ambiguous if it is just "id=software.id" and thus links on itself.
UPDATE
      software
SET purchprice = (SELECT purchprice
                  FROM softwarecost
                  WHERE softwarecost.id = software.id)
where EXISTS (SELECT purchprice
                  FROM softwarecost
                  WHERE softwarecost.id = software.id)

Answer: I know this is old, but I prefer
UPDATE software
SET purchprice = IFNULL( (SELECT purchprice
                          FROM softwarecost
                          WHERE id = software.id), purchprice)

It works as a general solution to the UPDATE with JOINs problem and saves SQLite having to execute the second SELECT statement to verify there actually is a row in the subquery.
Comment: This solution is shorter and doesn't repeat the query. But, I tested both and this one is, for some reason, orders of magnitude slower than the one with "WHERE EXISTS". So, only to use if speed is of no consequence.
Comment: That would actually make sense if NULLs were rare in column purchprice and the table was very large because SQL has to do a lot of searching for values when it doesn't need to.  So it is dependent on your data set on whether you anticipate mostly NULLs or mostly values already filled in.

If you have mostly already filled in values and the table is huge, you are taking a hit using this format SQL.

If the table is small, or mostly NULLs in the purchprice column, or maintainability is the primary concern of the SQL statement, then use this format SQL.
Comment: I am going to add one more comment on this.  In practice, there is usually some other condition to reduce the set of of values that the update statement would look at, such as all records that have been created today or particular batch numbers that would be specified in a where clause on the update statement itself to reduce the quantity of rows the update statement would look at.  Then, it can be approximately as efficient as the WHERE EXISTS version, but is easier to maintain.
Answer: Carter, the problem with >>near "s": syntax error<< is about the using of the ALIAS. The UPDATE command don't accept ALIAS. If you try bogdan tip about REPLACE, you can do the join into the SELECT clause.
Answer: Update software
  set Column1 = anyValue
  where id in (Select sf.id from software sf join softwarecost  sfc on sf.id=sfc.id
    where sfc.purchprice='anyValue'
  )

If you what to Update with Join and Where Condition
Answer: You can try as given,
UPDATE software SET purchprice = (SELECT purchprice FROM softwarecost a WHERE a.id =software.id) where purchprice IN(SELECT distinct(purchprice) FROM softwarecost a WHERE a.id = software.id)

Answer: There is no JOIN here:
UPDATE software
SET software.purchprice=softwarecost.purchprice
WHERE software.id=softwarecost.id

This will not work:
UPDATE software s INNER JOIN softwarecost sc on s.id=sc.id
SET s.purchprice=sc.purchprice

SQLite really does not support JOIN in UPDATE queries http://sqlite.org/lang_update.html
What about using REPLACE?
Maybe you could:
REPLACE INTO software
SELECT id, purchprice
FROM softwarecost

Comment: Hi Bogdan thanks for your relply , I'm getting this error.

SQLiteManager: Likely SQL syntax error: UPDATE software s INNER JOIN softwarecost sc on s.id=sc.id SET s.purchprice=sc.purchprice [ near "s": syntax error ]
Exception Name: NS_ERROR_FAILURE

Update with Join in SQLite


Ordered field consequence proof

Question: Hey can anyone help me get started on this proof?
Prove OFC7: for elements x,y in an ordered field, (-x)(-y) = x*y.
I am allowed to use the following axioms:
F1. x+(y+z) = (x+y)+z;
F2. x+y=y+x;
F3. there is a specified element 0 such that x+0=x;
F4. there is a specified element -x such that x+(-x)=0;
F5. x*(y*z)=(x*y)*z;
F6. x*y=y*x;
F7. there is a specified element 1 such that x*1=x and 1 does not equal 0;
F8. for any x not equal to 0, there is a specified element x^-1 such that x*(x^-1) = 1;
F9. x*(y+z)=x*y+x*z.
OFC1. If x+y=x+z, then y=z.
OFC2. -(-x)=x
OFC3. If x is not equal to 0 and xy=xz, then y=z.
OFC4. x*0=0
OFC5. If x*y=0 then x=0 or y=0.
0FC6. (-x)*y=-(x*y)
Comment: That's true in any ring. See [this math.SE answer for instance](http://math.stackexchange.com/a/137699/264) (and the question is likely a duplicate).
Answer: This is true in any field $F$ (not just ordered) and the proof is fairly standard.
Lemma: For all $x\in F$, $-x=(-1)x$.
Proof: $x+(-1)x=(1+(-1))x=0\cdot x=0=x+(-x)$ (by the distributive law) and then use cancellation.
It follows from the Lemma that $(-1)(-1)=-(-1)=1$ and hence $(-x)(-y)=(-1)x(-1)y=(-1)(-1)xy=xy$.
Answer: It is true in any ring.
We know that $(-x)y=-xy$ since $xy+(-x)y=(x+(-x))y=0y=0.$
Now $-xy+(-x)(-y)=(-x)y+(-x)(-y)=(-x)(y+(-y))=-x*0=0.$ That means that $(-x)(-y)$ is the negative of $-xy$, thus it must be $xy$.
Comment: Yeah the way to start is by using this (-x)(-y) + - (xy) = (-x)(-y) + (-x)y. Then after using the axioms (-x)(-y) = xy by F4 and F3.

Ordered field consequence proof


Subtheme update

Question: An update has become available for a given theme (Bootstrap Barrio). I had configured the previous release into a subtheme. How can I update the subtheme, or at least make a new subtheme of the updated one, and be sure that no modification performed in the old subtheme get lost?
Comment: I would follow the theme's upgrade guide: https://www.drupal.org/docs/8/themes/barrio-bootstrap-4-drupal-89-theme/bootstrap-barrio-installation/upgrade-barrio-from-8x-4x-to-5x-version#s-barrio-5x-upgrade
Answer: If you have made all the adjustments in the subtheme, I understand that there will be problems, because what will be updated is the parent theme.
Just confirm that the subtheme in the info.yml file has at least this:
bootstrap_barrio_subtheme.info.yml
<code>name: Bootstrap Barrio Subtheme
type: theme
description: 'Basic structure for a Bootstrap Barrio SubTheme.'
core: 8.x
core_version_requirement: ^8 || ^9 || ^10
base theme: bootstrap_barrio
</code>
Comment: Yes: `name` etc and, in particular, `base theme` are unvaried. But `version` still reads 5.5.6, rather than 5.5.16. The latter information was added automatically bu drupal packaging script at the time when the subtheme was created. Do I get it correctly, that the subtheme inherits all updates of the base theme and that, therefore, I shouldn't possibly worry much, provided my changes to the subtheme were mainly in style (choice of colors, regions to be activated, etc)?
Comment: That's right. If all your functionality is in the subtheme, everything will be fine. The problem would be if all your functionality was in the parent theme, because if it were updated, you could lose functionality. Greetings and God bless you.

Subtheme update


Flowers on a Piano

Question: We just moved a baby grand into our new house.  It's the Kawai I grew up with as a child. Very excited!
My wife was excited too.  It looked like a great surface to provide a little decoration on.  She prepared a vase of flowers for it.  I, needless to say, was not comfortable in the least with this plan, but I'd like her to be able to do something with it.
Does anyone have experience with flowers on pianos?  Do I need to stick with nice lightweight fake flowers, or are there ways to make sure the accidental spill does not ruin my finish (polyester)?  Perhaps plants that are comfortable with their moisture being stored in a damp sponge so it can't spill?  A happy wife makes a happy life, but there are some cases where care is needed when applying that aphorism!
Comment: I thought it would be interesting to find some examples: http://images.google.com/search?tbm=isch&q=grand+piano+in+room -- that brought me to http://capid.org/2013/07/23/placing-a-grand-piano/ , which offers some good wisdom, for example "Some people like having accessories on the piano. But it implies the instrument is not frequently used. A grand piano looks the best with its lid open."
Comment: Simple solution: always play the piano with the lid up. Find somewhere "sensible" to move the flowers to (i.e. not on the floor underneath the piano!) and when you are done, leave them there. But don't leave the lid permanently up, otherwise worse things may end up inside a piano than the problem you are trying to solve.
Comment: I'm confused. The intention is that you'll never play the piano with the lid up at all? If so then why have it? We owned a baby grand when I was growing up and it got played every day, which meant the lid was always at half stick at least. There was no way to put anything on it except sheet music.
Comment: I would not want a vessel of water anywhere near my piano.
Comment: Also the vase may sweat leaving coaster rings that may ruin the lid.
Comment: search on "wet floral foam" -- this at least alleviates the spilling problem.
Comment: I would personally not want to take a chance.  As a real estate agent, I can't tell you how many wood floors I have seen damaged under places where plants were placed.  Not sure if the water leaks out of the bottom of the pot or perhaps splashes during watering.  The pot itself can trap water under it an not allow it to be seen or to evaporate.  Silk plant gets my vote as a compromise.
Comment: There might be 1000 other places in your home to put flowers. Please don't have a piano be one of them.
Comment: The biggest risk is liquids. I used to put my glass of beer on the piano while I played, but nowadays I "play it safe" and put the beer elsewhere.
Answer: A piano generally has a really nice finish. It is a piece of (functional) furniture, not a shelf. At most, a plastic vase with plastic flowers (no liquid) placed on a fancy doily. Regular opening of the lid may dissuade others from putting things on the piano.
Answer: She means well.  Perhaps you could focus her good intentions towards a nice arrangement of dried flowers.

Flowers on a Piano


Mudar 'class' quando mudar a view

Question: Eu estou usando bootstrap e angular
Eu tenho um nav:

Übersicht

Produkte

Bestellungen

Einstellungen

Gostaria de aplicar a class active quando certa opção for selecionada. Como faria isso? Uso angularjs em meu sistema
Answer: Adicione a diretiva ui-sref-active, como no exemplo a seguir:

    Übersicht

Mudar 'class' quando mudar a view


Javascript variable what is less efficient

Question: I am learning Javascript currently.I was wondering if there is any difference between:

var factor=0.1;
var limit=10;
var x;
var y;

x= limit*factor;
y= limit*factor;

//or
var limit=10;
var x;
var y;

x=limit *0.1;
y=limit*0.1;

Does it make any difference (when looking at performance for example)? If so, why it is different? The second example looks less promising to me, because I keep thinking that I am declaring the variable 0.1 twice. Thanks for your help in advance.
Comment: No, there's no difference. The JavaScript engine should optimize both versions. Also, if there would be any difference it can safely be ignored. Just go for the one that is more readable.
Comment: If you change 0.1 to 0.2 you will need to update it in all places where you use it. So the first version is better.
Comment: in second example you are not declaring "0.1" twice and second would be more performant.
Comment: Do not start with optimization.
Comment: inline function, variable are always more performant but less reusable
Comment: any difference would be so Unsignificant i wouldn't care at all
Comment: Geez that was fast. Thanks for your comments guys
Comment: @binariedMe I will read more about infline function variables. Thanks
Comment: @Christy I guess the first one will do much better then. Thanks for replying.
Answer: There is a very small difference. When you use factor in the two multiplications, the JavaScript engine has to go look up the value of factor in the current lexical environment object each time — in theory, anyway; optimization may well be able to get rid of that, if and when the code is chosen for optimization by the JavaScript engine.
But regardless: Worry about performance problems when you have a performance problem to worry about. Instead, concentrate on readability and maintainability. If x and y are meant to be multiplied by the same value, put that value in something (a var, or perhaps a const with ES2015+), and use it in both places.
Comment: I always wondered (even though I know it's of **very** tiny nano small difference), but is it harder for js engines to get hardcoded values than one declared in a variable before hand ? I mean, I always use the variable way because for me it's less pain, and that I don't care so much how interpreter will suffer, but still, your answer doesn't tell exactly in which way this tiny difference goes. It could make sense that a declared variable is easier to clean, but it could also make sense that avoiding to declare something also avoids the need to clean it up.
Comment: @Kaiido: I have no idea how much more/less work it is for the *parser* to parse `0.1` vs. `factor`. I doubt there's any real difference. But the code only gets parsed once when loaded, after which the parsed result is either interpreted or compiled. So that parsing difference, if there is one, isn't going to matter, whereas the symbol lookup could. (Just a few months ago I would have said that virtually no JavaScript engine uses an interpreter anymore, but recently V8 went back to interpretation -- bytecode-level, like Java -- for code that's only used rarely.)
Comment: @T.J Crowder I see , I did not really expect that it would be looked up twice.. But the first example is much more readible, so I will consider readibilty.. thanks for replying!
Comment: @samid: Well, if there's *any* optimization applied, it probably won't be. :-)
Comment: PS: (And of course maintainability, If I had alot of multiplications the first would damage my fingers less.
Answer: I would suggest you go ahead with the first example, but with a modification. Variables are meant to hold dynamic data, it is better to hold 0.1 in a variable, so you can change it over time if required.
// have a function so that you don't repeat the code
function getFactor(factor, limit) {
  return limit * factor;
}

//declare the variables and set the required default values
var factor = 0.1,
    limit = 10,
    x, y;

//assign getFactor to x and y variables
x = y = getFactor(factor, limit);

Comment: Question must have been updated, both examples use `var`.
Comment: @T.J.Crowder zzzz, unfortunately, yes, thanks... will modify my answer.
Comment: @Mr.Alien My mistake, but thanks for anwering in any case!


How to calculate average of salary using minimum salary and maximum salary columns

Question: To elaborate, i have a job post table with company name, designation , min salary, max salary, min experience , max experience etc.
For a concerned role i am trying to give out average salary and experience .
I wanted do list out the company name(xxx) with role database developer offering average sal and average experice.

declare user_details cursor FOR
   select up.role,ur.years,ur.month,upd.current_ctc from user_registration ur
   left join user_personal_details upd on upd.registration_user_id=ur.iduser_registration
   left join user_projects up on up.employee_id=ur.iduser_registration
   where ur.iduser_registration=p_userID;
  open user_details;
  fetch user_details into v_role,v_exp_years,v_exp_months,v_current_ctc;
  #select v_role,v_exp_years,v_exp_months,v_current_ctc;
  set v_experience= concat(COALESCE(v_exp_years,0),'.',COALESCE(v_exp_months,0));
  #select v_experience;
   BLOCK2: BEGIN
    declare jobs_list cursor for
     select jobid,cr.company_name,jp.max_salary from job_posts jp
     join client_registration cr on cr.idclient_registration=jp.idclient_registration
     where jp.designation=v_role
     and v_experience between jp.min_experience and jp.max_experience
     group by jp.jobid order by jp.createdon limit 5;

    DECLARE CONTINUE HANDLER FOR NOT FOUND SET v_finished = 1;
     OPEN jobs_list;
     set v_result_joblist='';
     set v_result_role_list='';
     jobs_list_loop: LOOP
     FETCH FROM jobs_list INTO v_jobID,v_company_name,v_max_salary;

      IF v_finished=1 THEN LEAVE jobs_list_loop;        END IF;
      set  v_result_joblist=concat(v_result_joblist,v_jobID,'-',v_company_name,'-',v_max_salary,',');

       if(v_result_role_list is null or v_result_role_list='') then
        set v_result_role_list= v_company_name;
       else
        set v_result_role_list=concat_ws('-',v_result_role_list,v_company_name);
       end if;
        BLOCK3: BEGIN
         declare role_wise_jobposts cursor for
          select jp.designation,max(jp.max_salary),min(jp.min_salary),max(jp.max_experience),min(jp.min_experience) from job_posts jp
          join client_registration cr on cr.idclient_registration=jp.idclient_registration
          where cr.company_name=v_company_name
          group by jp.designation order by jp.createdon;

          DECLARE CONTINUE HANDLER FOR NOT FOUND SET v_finish = 1;

          OPEN role_wise_jobposts;
           role_wise_joblist: loop
           FETCH FROM role_wise_jobposts INTO v_role_list,v_max_salary,v_min_salary,v_max_exp,v_min_exp;

           IF v_finish=1 THEN                LEAVE role_wise_joblist;              END IF;
           set v_result_role_list=concat_ws(',',v_result_role_list,concat('_',v_role_list),v_max_salary,v_min_salary,v_max_exp,v_min_exp);
          END LOOP role_wise_joblist;
           set v_finish=0;
           set v_result_role_list=concat_ws('-',v_result_role_list);
          CLOSE role_wise_jobposts;
           #select v_result_role_list;
        END BLOCK3;

       #select v_result_role_list;
    END LOOP jobs_list_loop;

   END BLOCK2;
 close user_details;
 select v_result_joblist UNION select v_result_role_list;
END
Comment: Please share some table data with us.  It strikes me as strange to be storing max and min values.
Answer: Make a query like this:
SELECT avg(col1 + col2)
FROM test
WHERE uid=5;

SQL Fiddle Demo
Comment: select avg(min_salary+max_salary), min_salary,max_salary from job_posts group by jobid
Comment: Hi Mayank thaks for the reply   select avg(min_salary+max_salary), min_salary,max_salary from job_posts group by jobid This is not returning me correct result


Regex to parse certain information from email text

Question: I have created a google app script to search and extract text from emails based on filtering logic and put the text into a local html file. I want to extend this to take certain elements from the text in this form email and push it into a google sheet, which I can do, but I'm having trouble getting the regex right to grab the elements I need from the form email. Here's an example of the form email with the values I want to isolate with regex bolded. Any help is very much appreciated.
SC Assigned for Oppty with Any Company
URL to the Oppty: https://my.salesforce.com/0062J00000rsx85 Opportunity Overview: Any Company / GBP 1,000.00 Opportunity Type: New Business Opportunity Owner: Jane Doe Sales Consultant(s): Jon Doe Lead Source: Cold Call Close Date: 9/30/2022 Stage: 1. Initial Call Setup Next Steps: Demo scheduled
Comment: You might want to have a look into lookahead and lookbehind.
Comment: If you can define a rule at/around which point of the text the information is, you can write a regular expression for it. For example, company name is after "with" but before "URL", Name is after "Owner:" but before "Sales", etc.
Answer: Something like this:
<code>/(?<=with ).*(?= URL)|(?<=Type: ).*(?= Business)|(?<=Owner: ).*(?= Sales)|(?<=Stage: ).*(?=. Initial)/g
</code>


Configuration Tuning for PostgreSQL 9.1 PostGIS 1.5 Ubuntu 12.04 Server

Question: My server performance is poor. At times SSH, top, and other features or commands are very slow to respond, taking several seconds or more. A query that normally takes 5 minutes can sometimes take 30 minutes. The database is mostly being used to do a spatial query (grid and summarize) on approximately 500GB of stored data spread between 4 tables. Restarting the server works as a temporary fix, but cannot be used as a long term solution.
Any suggestions for how to diagnose and solve my performance issues?
Hardware and Configuration:

3.3 GHz Intel quad core i5
16 GB DDR3 RAM
6 TB software RAID 10 (6 x 2 TB drives)
Ubuntu 12.04 64-bit
Postgres 9.1
PostGIS 1.5
Comment: Hi Martin, did you find the bottleneck at the end? Let us know.
Comment: There is definitely a hardware error, which while very intermittent is critical. I have not isolated the issue yet, software development was given priority over server stability, but I will revisit this before the end of the year and report back.
Comment: Looks like it was in part at least due to one bad hard disk in the software RAID. I also switched to Debian and am now using a GPT partition table. Everything is working great.
Comment: OK, thank you for the feedback! Just one question, have you tried to build the Nominatim database on your infrastructure? How much time does it take? http://wiki.openstreetmap.org/wiki/Nominatim/Installation
Comment: I haven't tried to build the Nominatim database. The machine is gone into use and I cannot take it down. I will need to use Osmosis at some point and will post benchmarks then. Thank you. http://wiki.openstreetmap.org/wiki/Osmosis
Answer: Did you tune your PostgreSQL server or are you using it OOTB after doing an apt-get install postgresql-server?
PostgreSQL is known for being installed with very, very conservative settings. You can gain a lot by properly tuning your server. Luckily there's an excellent post on this by the guys from opengeo:
http://workshops.opengeo.org/postgis-intro/tuning.html
Comment: I did tune the PostgreSQL server with 4GB of shared buffers and using the other settings recommended here: http://http://jaspreetchahal.org/setting-up-your-own-openstreetmap-server/ since the database includes the OpenStreetMap planet dump. There might be a hardware problem with the OS hard disk, which is not part of the RAID. I've ordered some new hardware to test that out and will post updates.


Hypothesis testing a location shift in heteroscedastic and non-normal data

Question: How do I test for a "location shift" in something like the mean or median if the shape of the distribution has changed quite significantly between groups?
Often an experimental intervention seems to completely change the distribution of the data. For example, If I measure limb length in control and toxin-exposed animals, the control group sample might appear to be drawn from a symmetric, normal distribution but the experimental group might be heavy-tailed and have much more dispersion.
All the statistical tests I am familiar with either assume that the data is drawn from normally-distributed populations or that the data is drawn from two populations with non-normal but identical distribution shapes.
I can do something like a two-sample Kolmogorov-Smirnov test which tells me that my groups differ. But this isn't telling me anything about location, right?
Comment: Yashka - The two sample K-S test *can* tell you about location-shift type difference; you can get either a point estimate or a confidence interval. It won't tell you the individual locations though.
Comment: @Glen_b You're thinking of the goodness-of-fit test; there's a K-S test for comparing two samples too.
Comment: Indeed, there is, but it's almost invariably referred to as the *two sample* K-S test - to avoid exactly this problem (or sometimes, just 'the Smirnov test'), which is what threw me. Thanks.
Answer: You are correct that a K-S test deals with the shape of the populations and not the location.
Before I suggest a strategy to try, consider this: if there is a substantial change in the shape of the distribution then is the location really what you want to know about? Is a  test of a hypothesis relating to the location of any inferential utility?
If you answer yes to those questions, then if you have lots of data, current and past, try a couple of simple transformations to see if you can make the likely population shapes similar. (I always like a log transformation for heteroscedastic data.) Once the populations are tolerably similar use either a permutations test or a Student's t-test on the location and trust that the robustness of those tests will deal with any non-identicalness and non-normality respectively.
Your conclusions should be carefully calibrated taking the nature of the data in mind. A significance test approach where the P-value is interpreted as an index of the strength of evidence against the null is much more useful in such circumstances than a Neyman-Pearson hypothesis test which yields a binary outcome.
Comment: biologically, it makes sense that the bone has an average size under normal conditions. The fact that our toxin makes it shorter with more variability than exists without an intervention is not really surprising. If this were a factor that made the bone **bigger** with increased variability I would simply use a log transform.
Comment: Good point. Perhaps a reciprocal transform would help, but I have no experience with it.
Comment: I would commend quantile-quantile plotting for initial comparison of distributions here. The original key paper Wilk, M. B. and Gnanadesikan, R.. 1968. Probability plotting methods for the analysis of data. _Biometrika_ 55: 1-17 remains a source of inspiration. http://www.stata-journal.com/sjpdf.html?articlenum=gr0027 gives some more recent references.
Answer: The modified Mathisen test (Hettmansperger & McKean (1998), Robust Nonparametric Statistical Methods, Ch. 2.11) tests for equal medians under the null hypothesis while making no assumptions about the distributions of either sample other than that they're continuous.
But do bear in mind what @Michael said—a difference in medians is usually interesting only when you think there's a location parameter shifting. More often in your situation people use the Mann–Whitney–Wilcoxon test to assess stochastic dominance: that's whether one group has a lower or higher cumulative distribution function of the response for all its values & would correspond to the idea of seeing whether the toxin has a good, a bad, or not much effect. The assumption here is that the population cdfs don't cross, & is usually checked by examining a plot of the sample cdfs.
Comment: I had not heard of stochastic dominance before but it seems like a good concept to apply to these situations.


Pearson correlation is not significant although effect is .30 What could be the reason?

Question: I have a correlation between two variables of 0.30, hence a medium effect. but it is not statistically significant and I want to report the reasons for that. looking at the test statistic I see that the sample size (as in all test statistics) has an influence. But what else could be the reason? Does the standard deviation or standard error have an influence?
edit: Thank you for your helpful and fast answers!
Answer: It is the sample size. For a simple correlation between two variables, the coefficient and sample size are the only pieces of information that you need in order to compute the standard error, and hence assess statistical significance. So if the coefficient does not differ significantly from zero despite being a canonical "medium" sized effect, then the only other culprit can be the sample size.
Answer: The size of the correlation coefficient doesn't tell you something about the significance of the effect. Look at the Wiki page about the Fisher transformation. As Jake Westfall pointed out, only the correlation coefficient $r$ and the sample size $n$ are used to calculate the standard error $SE=1/\sqrt{n-3}$ and the $z$-value which is then used to calculate the $p$-value. As you can see from the formula for the standard error, at least 4 observations are necessary to use Fisher's transformation.


How do I update a Node.js native addon to use the new API?

Question: There's an old Node.js native addon that I need for my work, but no longer works for Node.js 12 and above because of deprecation of many native APIs. Out of dozens of errors, I have fixed all but one, which has to do with initializing and calling a callback function. The new API requires 4 arguments, while the old one had three. This is the broken code:
void node_mpg123_feed_after (uv_work_t *req) {
  Nan::HandleScope scope;
  feed_req *r = (feed_req *)req->data;

  Local<Value> argv[1];
  argv[0] = Nan::New<Integer>(r->rtn);

  Nan::TryCatch try_catch;

  Nan::New(r->callback)->Call(Nan::GetCurrentContext()->Global(), 1, argv); //Compilation error in this line

  // cleanup
  r->callback.Reset();
  delete r;

  if (try_catch.HasCaught()) {
    FatalException(try_catch);
  }
}

Specifically, note the new API, which uses 4 arguments, and contrast it with the old one, which needs only three. I can't figure out what parameters to put in, since essentially no tutorials exist on the internet for the new API, and the internet is filled with examples of the old broken one.
Can anyone point me in the right direction? The exact error message I am getting is error C2660: 'v8::Function::Call': function does not take 3 arguments in the line I marked with the comment above.
Comment: Oof, porting an 0.8 API to current.  I haven't delved in this in a long time, but perhaps there's some useful nuggets here that might help? https://stackoverflow.com/questions/45900692/how-to-use-the-same-context-across-multiple-functions-in-v8-javascript
Comment: It's not necessarily a 0.8 API, but it matches the signature of what worked up until node 10. Thanks for the link, I'll check it out.
Answer: After going through the nan changelog reading the nan sources, I found a new way of calling callbacks. Specifically, the line:
Nan::New(r->callback)->Call(Nan::GetCurrentContext()->Global(), 1, argv);

becomes
Nan::Call(Nan::New(r->callback), Nan::GetCurrentContext()->Global(), 1, argv);


How should I resample the training and testing set with imbalanced data whilst having meaningful performance metrics?

Question: I have an imbalanced dataset of approx. 200 positive and 800 negative examples.
I run nested cross-validation where i=5 and j=5; (i is inner and j is outer).  The cross-validation procedure isn't the problem.
For each outer-CV iteration, I randomly split the dataset into 80% training and 20% testing, thus giving 160 positive and 640 negative training examples each time, whilst leaving 40 positive and 160 negative examples in the testing set.  However, I then down-sample the training set to balance it to 160 positive and 160 negative samples (remember, it was already in random order).  This testing set represents the natural distribution of the positive and negative classes as found in nature.  Therefore, in a real world scenario, the classifier will need to correctly predict novel data input with this ratio.
However, with the imbalanced testing sets, I experience poor performance in terms of F1 (e.g. 0.50), MCC (e.g. 0.30), and etc. on the positive class (negative class performance is good, but not useful).  On the other hand, if I also balance the testing set (which would not represent nature) then I receive good performance (e.g. F1 0.75, MCC 0.50).
Why do I receive poor performance on the natural test distribution, when clearly the classifier is able to discriminate between the two classes, as I tested by also balancing the testing sets?
What is the appropriate solution to solve this problem?  Is it solvable?
Is it a problem of poor features?  Is it a problem which SVM cannot solve?
Edit: The first answer below contains useful and interesting information, but it does not actually answer the question:  Why are the classification performance metrics generally poor when testing the natural distribution, given that a good decision boundary has clearly been found?  This is not a problem of optimizing C or G because I tried to optimize for the positive class but it had almost no effect.  Class weights would not work either - classification is fine with a balanced testing set.  Also, I am already using probabilistic SVM.
Comment: You have miscast this as a [forced-choice classification problem](https://fharrell.com/post/classification) instead of a probability estimation problem, and that has led to the problems you see.
Answer: Why do I receive poor performance on the natural test distribution, when clearly the classifier is able to discriminate between the two classes
SVM doesn't try to optimize the performance of any single outcome (i.e. positive or negative). It attempts to produce the 'best' classification overall.
This is done by dividing the dataset into two regions with the region determining how to classify points. In order to do this SVM tries to finds a 'good' hyperplane (boundary) between the two regions. SVM defines 'good' as a balance between a split that accurately classifies data points (minimizes hinge loss) and a split that maximizes the size of the 'margin' (distance between closest correctly classified negative point and the boundary plus the closest correctly classified positive point and the boundary).
Kent Munthe Caspersen gives a great explanation of this in the following thread. "What is the influence of C in SVMs with linear kernel?".
If you add additional training data (of a single class) you will potentially do two things to the costs being minimized by SVM.
1. you could increase the number of points misclassified in that class (increasing ridge cost)
2. you could decrease the margin (also increasing cost as SVM tries to maximize the margin)
in order to compensate for the increased cost the optimal boundary would move to more accurately predict the class of data added. this would naturally come at the cost of the accuracy of the remaining class.
What is the appropriate solution to solve this problem? Is it solvable?
The most appropriate solution depends on your goals. Though my bias is normally to use a probabilistic classifier of some type if possible as there is normally the option to collect more data about an observation before classifying it.
Assuming SVM is the best classifier for your purposes. You can weight the costs of the objective function SVM is minimizing.
If your implementation of SVM supports adding weights to the cost function of the SVM then that can be used otherwise duplicating the positive class would produce an equivalent effect to weighting the cost function. You would want to duplicate 4 times in order to make positive errors 4 times as important as it currently is (and therefore balanced with negative).
Is it a problem of poor features?
No
Is it a problem which SVM cannot solve?
see above
Answer: One problem could be using a different metric for evaluating test performance than training. SVM is optimizing empirical missclassification error that tries to minimize the absolute number of correct classifications, regardless what are the proportions in each class, whereas F1 could be penalizing more the errors in the less prevalent class (based on quick look at F1).
When optimizing on the natural proportion, the classifier is biased to the prevalent class (because of optimizing the empirical error) and F1 decreases because of that.
Your goal seems to be give more importance to less prevalent class. I suggest define the train objective that reflect your goals and evaluate both train and test based on same metric.
Adjusting training proportions is one way for achieving that (in this case, you should see improvement in the natural test evaluated with a more balanced metric. Have you checked confusion matrices?). Another is to weight the samples, so that you are able to use all training set.
Answer: Why are the classification performance metrics generally poor when testing the natural distribution, given that a good decision boundary has clearly been found?
The classifier has found a good decision boundary for a balanced dataset from training with one.
Surely, balancing training data can improve model performance on the natural, imbalanced scenario, but that's not necessarily going to happen, as it's dependant on the distribution of the balanced set and the classifier's hyperparameters.
What is the appropriate solution to solve this problem? Is it solvable?
From your question, I assume you haven't tried various approaches for balancing your dataset. I'd suggest using SMOTE, Tomek Links and Nearest Neighbours-based methods if you haven't already.
Comment: I have no idea why people claim that balancing training data can improve models. See https://stats.stackexchange.com/questions/357466/are-unbalanced-datasets-problematic-and-how-does-oversampling-purport-to-he
Comment: @JTH - I think that a primitive learner and default loss function might do poorly on imbalanced data, and that balancing the training data can compensate for lack of expertise in those; not as much by making it good as by making it less bad.


How to understand this variable change in a double integral?

Question: I am solving the following problem:
$$\int_{0}^{1}\int^{1}_{0}\frac{dx\cdot dy}{x^{-1}+|\ln(y)|-1}\leq 1.$$
After showing that $x^{-1}-1\geq |\ln(x)|$ for $x\in (0,1]$  we get that
$$\int_{0}^{1}\int^{1}_{0}\frac{dx\cdot dy}{x^{-1}+|\ln(y)|-1}\leq \int_{0}^{1}\int^{1}_{0}\frac{dx\cdot dy}{|\ln(x)|+|\ln(y)|}
=\int_{0}^{1}\int^{1}_{0}\frac{dx\cdot dy}{|\ln(x\cdot y)|}.$$ Now in the solution I see the following variable change $y=u/x$ which should imply (according to the author) that
$$\int_{0}^{1}\int^{1}_{0}\frac{dx\cdot dy}{|\ln(x\cdot y)|} \color{red}{=}
\int_{0}^{1}\left(\int^{1}_{u}\frac{dx}{x}\right)\frac{du}{|\ln(u)|}.$$ I am not sure how this happened. Could someone please explain this?
Answer: Since $x=u/y$, $u\le x\le 1$. Further, $dy=d(u/x)=du/x$, so the result follows.
Answer: We are going from $xy$ plane to $xu$ plane.
The rectangle $0\le  x\le 1$, $0\le  y\le 1$, under transformation $x=x$, $y=u/x$
 transforms to the triangle $0\le  x\le 1$,  $0\le  u\le x$ which is then described as $0\le  u\le 1$,  $0\le  x\le u$
Note that the upper side of the rectangle $y=1$ maps to the upper side of the triangle namely $u=x$


How to post a button's value in html form (PHP)

Question: i have javascript that changes an input's value and when i post the form, the field is not transferred
<input id="exampleID" type="button" name="exampleButton" value="click me" onclick="changeValue()">

when the button is clicked the value (displayed to the user) changes to "Clicked"
then when i post the form it the value is left behind
if(isset($_POST['exampleButton'])) {
    echo "true";
}

this doesn't echo anything
what should i do?
Answer: You can change value of hidden field:

<input id="exampleID" type="hidden" name="exampleButton" value="">
<input type="button" value="click me" onclick="changeValue()">

Answer: The input button control won't send any value to the server on submit, as it is made to interact with javascript. If you need to send a dynamic value, store it in a field (like an input hidden control), or, if you insist to send it through a button, change its type to submit


How can I show the camera but not let the user take a photo?

Question: How can I let the user see the front facing camera, but prevent them from being able to take a picture, video, or switch to the rear camera on the iPhone 4/4s and/or the iPod Touch 4?
Answer: <code>cameraPicker = [[UIImagePickerController alloc] init];
....
cameraPicker.showsCameraControls = NO;
cameraPicker.cameraDevice = UIImagePickerControllerCameraDeviceFront;
</code>
Comment: When I copy the code in, it says that it cant find cameraPicker.  what else do I need to do?
Comment: @coryginsberg answer edited. a UIImagePickerController object.
Answer: You can use AVFoundation framework to open camera.
Try this sample code https://developer.apple.com/library/ios/#samplecode/AVCam/Introduction/Intro.html#//apple_ref/doc/uid/DTS40010112 .


does node_save wait until end of php session to create db record?

Question: Is it possible/expected that node_save() does not create a new record until the current php session is complete?
In other words, if i have a set of nodes to create and i need to check something that is based on the entire list of nodes prior to creating each one; the ones i am creating in my script will not yet be included in the full list?
Answer:
Is it possible/expected that node_save() does not create a new record until the current php session is complete?

I'm not sure 'session' is the right word there, I'm assuming you mean 'current request' (queuing actions to be run when the session has expired would be an odd thing, and not something PHP/Drupal would do without you telling it to).
Either way, before node_save() completes it commits the database transaction and flushes relevant caches. So no, it doesn't wait for the current request to complete.
So to address

the ones i am creating in my script will not yet be included in the full list?

No, once you've saved the node, and assuming it completed without error, it will be in the database and available immediately via node_load().
Of course you don't actually need to load it, as your $node object will be in an identical state to the loaded node when node_save() has completed anyway.
Ignoring all that, if you actually mean "does running node_save() automatically update an array of nodes I've previously loaded into a variable earlier in the script", then also no. That would be magic :)
Comment: Yes, you understand what i am doing.. and no, it does not appear to work that way from what i see.. i stop execution AFTER the node_save() call has completed and the record has not been added to my db (even though i have a nid assigned. later in the code i do a entityfieldquery to pull a list of nodes and this "new" node is not in my list (which makes sense as it is still not in the db).
Comment: If it has a nid but isn't in the database then you've got bigger problems. The db engine provides Drupal with that nid, so if it's giving you an id, but not storing the data, there's something wrong with it


purrr map / lapply / sapply across groups of multiple (n > 1) elements at a time?

Question: Suppose we have a vector, we can easily enough lapply, sapply or map across 1 element at a time.
Is there a way to do the same across groups of (>1) elements of the vector?
Example
Suppose we are constructing API calls by appending comma-separated user_identifiers to the URL, like so:
user_identifiers <- c("0011399", "0011400", "0013581", "0013769", "0013770", "0018374",
  "0018376", "0018400", "0018401", "0018410", "0018415", "0018417",
  "0018419", "0018774", "0018775", "0018776", "0018777", "0018778",
  "0018779", "0021627", "0023492", "0023508", "0023511", "0023512",
  "0024120", "0025672", "0025673", "0025675", "0025676", "0028226",
  "0028227", "0028266", "0028509", "0028510", "0028512", "0028515",
  "0028518", "0028520", "0028523", "0029160", "0033141", "0034586",
  "0035035", "0035310", "0035835", "0035841", "0035862", "0036503",
  "0036580", "0036583", "0036587", "0037577", "0038582", "0038583",
  "0038587", "0039727", "0039729", "0039731", "0044703", "0044726"
)

get_data <- function(user_identifier) {
  url <- paste0("https://www.myapi.com?userIdentifier=",
                paste0(user_identifier, collapse=","))
  fromJSON(url)
}

In the above, get_data(user_identifiers) would return the APIs response for all 60 user_identifiers in one single request.
But suppose the API accepts a maximum of 10 identifiers at a time (so we cannot do all 60 at once).
A simple solution could be to simply map/lapply/sapply over each element, e.g. sapply(get_data, user_identifiers - this would work fine - however, we would make 60 API calls, when all we really need is 6. If we could map/lapply/sapply over groups of 10 at a time; that would be ideal
Question
Is there an elegant way to map/lapply/sapply over groups of n elements at a time (where n>1)?
Answer: We can split user_identifiers in groups of 10 and use sapply/map/lapply
sapply(split(user_identifiers, gl(length(user_identifiers)/10, 10)), get_data)

where gl creates groups from 1 to 6 each of length 10.
gl(length(user_identifiers)/10, 10)
# [1] 1 1 1 1 1 1 1 1 1 1 2 2 2 2 2 2 2 2 2 2 3 3 3 3 3 3 3 3 3 3
#     4 4 4 4 4 4 4 4 4 4 5 5 5 5 5 5 5 5 5 5 6 6 6 6 6 6 6 6 6 6
#Levels: 1 2 3 4 5 6

The same groups can be created with rep
rep(1:ceiling(length(user_identifiers)/10), each = 10)

As @thelatemail mentioned, we can use cut and specify number of groups to cut the data into
sapply(split(user_identifiers, cut(seq_along(user_identifiers),6)), get_data)

Comment: Also `cut` - `cut(seq_along(user_identifiers),10)` for cutting into *n* groups.


Apache2 Reverse Proxy Keeps Giving Error 500

Question: No really sure whats happening when I try and reverse proxy but I keep getting Error 500. I have mod_proxy and mod_proxy_html enabled and my conf file for the reverse proxy looks as so:
    ProxyRequests Off
    ProxyPreserveHost On
    <Proxy *>
     Order deny,allow
     Allow from all
    </Proxy>
    ProxyPass /panel http://mydomain.com:8005/
    ProxyPassReverse /panel http://mydomain.com:8005/

I've tried pretty much everything as far as writing the reverse differently with and without the slashes. When I
    tail /var/log/apache2/error.log

    [Tue Dec 06 12:58:00 2011] [warn] RSA server certificate is a CA certificate (BasicConstraints: CA == TRUE !?)
    [Tue Dec 06 12:58:00 2011] [notice] suEXEC mechanism enabled (wrapper: /usr/lib/apache2/suexec)
    [Tue Dec 06 12:58:00 2011] [notice] Digest: generating secret for digest authentication ...
    [Tue Dec 06 12:58:00 2011] [notice] Digest: done
    PHP Deprecated:  Comments starting with '#' are deprecated in /etc/php5/apache2/conf.d/ming.ini on line 1 in Unknown on line 0
    PHP Warning:  PHP Startup: Unable to load dynamic library '/usr/lib/php5/20090626+lfs/sqlite.so' - /usr/lib/php5/20090626+lfs/sqlite.so: cannot open shared object file: No such file or directory in Unknown on line 0
    [Tue Dec 06 12:58:00 2011] [notice] mod_python: Creating 8 session mutexes based on 150 max processes and 0 max threads.
    [Tue Dec 06 12:58:00 2011] [notice] mod_python: using mutex_directory /tmp
    [Tue Dec 06 12:58:00 2011] [warn] RSA server certificate is a CA certificate (BasicConstraints: CA == TRUE !?)
    [Tue Dec 06 12:58:00 2011] [notice] Apache/2.2.20 (Ubuntu) DAV/2 mod_fcgid/2.3.6 Phusion_Passenger/2.2.11 PHP/5.3.6-13ubuntu3.2 with Suhosin-Patch proxy_html/3.0.1 mod_python/3.3.1 Python/2.7.2+ mod_ruby/1.2.6 Ruby/1.8.7(2011-06-30) mod_ssl/2.2.20 OpenSSL/1.0.0e configured -- resuming normal operations

Comment: Maybe the proxy is passing correctly, and it is the destination server that is giving the 500 error? What does the logs on the destination server look like?
Comment: Can you access from the proxy server http://mydomain.com:8005/ URL? E.g. try with wget: `wget -O - -S http://mydomain.com:8005/` or `curl -i http://mydomain.com:8005/`
Comment: Maybe a typo, maybe not, but there is no `mod_proxy_html`. In case you (tried to) enabled this ensure you don't get an error right there. It should be `mod_proxy_http`.
Comment: Okay, thanks @Chris  not sure why I wasn't noticing that.
Answer: Make sure mod_proxy and mod_proxy_http are loaded.
Answer: In a reverse proxy, ProxyRequests should be set to off.  See the mod_proxy documentation.
Comment: Sorry I wrote it on here wrong, ProxyRequests is set to off. Also the other server isn't even showing that a connection attempt is being made.
Comment: How do you know that the connections is not made? Are you using a network sniffer like WireShark between proxy and web server?
Comment: I am running a Tornado Web Server. So right now I am starting the server in a terminal which will show any type of requests made to the server. If I go to the server on its own port it shows the request was accepted with no error, if I go through the reverse proxy the Tornado server shows nothing but the website throws up a Error 500
Answer: A couple of possibilities:
I know it sounds simple but this could be DNS issue.
Is mydomain.com resolvable from the proxy?
From the proxy ping mydomain.com.  What IP does it resolve to and is port 8005 open on that IP address.
I typicall eliminate DNS by using IPs when possible while debugging.
Also, try turning ProxyPreserveHost off.  I am not familar with your backend server but perhaps it does not respond if the Host: doe not match the IP domain it is configured to use.


How to display the translated value of a boolean field when viewing a translated page?

Question: I have this problem with translation of a custom checkbox (boolean) field. To be specific, I'm able to translate everything but the options (Yes / No) that are shown on node view page.
I have the modules locale, i18n_nodes, and i18n_fields enabled, and translation strings imported (with corresponding context and to appropriate textgroup), and default language set to English. The translation shows correctly everywhere but on node view where it's still untranslated.
The content type is custom and is created via hook_node_info() and it's fields via field_create_field, and field create_instance.

BTW: I don't need translation of the content (every node will always have just one language and should be accessible regardless of what language the user has selected) but only of the user interface (descriptions, titles, ...). So if there's a simpler way to translate my custom fields and content types, please let me know.

Screenshot proofs that I've done everything I could:
Settings:

Edit page:

View page (note the only string that is in English but should be in Czech and should be Aktivni)
Comment: That's odd. Have you tried translating the string with [Localization Client](https://www.drupal.org/project/l10n_client)?
Comment: @othermachines tried that but it didn't work with fields at all... (it showed circa 50 % of field related strings on page) and of course if found nothing for "Active"...
Answer: Try what's mentioned in Comment #1 of issue # 1762488, i.e:

... visit 'Manage Display' and switch from "Default" to "Default translated".
Comment: Thanks for the accept! Looks like that was the missing piece of your i18n 'puzzle' ... Oh well, multilanguage sites, so much things to know and remember to make it work ... Anyway, I slightly enhance the title of your question also, to ake it more accurate, ok?
Comment: Yep, that looks better and thanks for the info. I wouldn't have found out about that myself :).
Comment: "Merci" (oeps, no French here ...: thank you) ... To be honest, when I first saw your question, it occured to me that I never ran into such (detailed) translation issue. So I learned from it myself also, for new time I have a similar field ... Note: I might soon "investigate" http://drupal.stackexchange.com/search?q=user%3A17790+is%3Aq


Dependency Injection Query

Question: I'm starting a web application that contains the following projects:
Booking.Web
Booking.Services
Booking.DataObjects
Booking.Data
I'm using the repository pattern in my data project only. All services will be the same, no matter what happens. However, if a customer wants to use Access, it will use a different data repository than if the customer wants to use SQL Server.
I have StructureMap, and want to be able to do the following:
Web project is unaffected. It's a web forms application that will only know about the services project and the dataobjects project.
When a service is called, it will use StructureMap (by looking up the bootstrapper.cs file) to see which data repository to use.
An example of a services class is the error logging class:
public class ErrorLog : IErrorLog
{
    ILogging logger;

    public ErrorLog()
    {

    }

    public ErrorLog(ILogging logger)
    {
        this.logger = logger;
    }

    public void AddToLog(string errorMessage)
    {
        try
        {
            AddToDatabaseLog(errorMessage);
        }

        catch (Exception ex)
        {
            AddToFileLog(ex.Message);
        }

        finally
        {
            AddToFileLog(errorMessage);
        }
    }

    private void AddToDatabaseLog(string errorMessage)
    {
        ErrorObject error =
            new ErrorObject
            {
                ErrorDateTime = DateTime.Now,
                ErrorMessage = errorMessage
            };

        logger.Insert(error);
    }

    private void AddToFileLog(string errorMessage)
    {
        // TODO: Take this value from the web.config instead of hard coding it
        TextWriter writer = new StreamWriter(@"E:\Work\Booking\Booking\Booking.Web\Logs\ErrorLog.txt", true);
        writer.WriteLine(DateTime.Now.ToString() + " ---------- " + errorMessage);
        writer.Close();
    }
}

I want to be able to call this service from my web project, without defining which repository to use for the data access. My boostrapper.cs file in the services project is defined as:
public class Bootstrapper
{
    public static void ConfigureStructureMap()
    {
        ObjectFactory.Initialize(x =>
        {
            x.AddRegistry(new ServiceRegistry());
        }
        );
    }

    public class ServiceRegistry : Registry
    {
        protected override void configure()
        {
            ForRequestedType<IErrorLog>().TheDefaultIsConcreteType<Booking.Services.Logging.ErrorLog>();
            ForRequestedType<ILogging>().TheDefaultIsConcreteType<SqlServerLoggingProvider>();
        }
    }
}

What else do I need to get this to work? When I defined a test, the ILogger object was null.
Comment: Take a look at this answer: http://stackoverflow.com/questions/589374/how-to-use-dependency-injection-with-asp-net/3849338#3849338
Answer: Perhaps some details on how you are calling this code from a test would be useful.
My understanding is that you need to ensure that the ConfigureStructureMap call has been made early in the applications life (e.g. in the Global.asax in a web project).
After that you would be calling for instances of IErrorLog using something like:
IErrorLog log = StructureMap.ObjectFactory.GetNamedInstance<IErrorLog>();

Dependency Injection Query


In a uniformly convex Banach space $x_n\stackrel{w}\to x$ and $||x_n||\to ||x||$ implies $||x_n-x||\to 0$

Question: In a uniformly convex Banach space $$x_n\stackrel{w}\to x  \ \ \text{and} \ \ ||x_n||\to ||x||  \ \ \text{implies}  \ ||x_n-x||\to 0.$$ Can you  help me to solve it?
Thanks in advance.
Comment: @RobertLewis $x$ is a specific value, the weak limit. It might have been less confusing if that had been called $x_\ast$ for example, then I would have written $\lambda(x_\ast) = \lVert x_\ast\rVert$. It's just the value at one point that I prescribe.
Comment: It may help if you assume $\lVert x\rVert = 1$, since that may make things closer to the definition of a uniformly convex space. What can you say about $x+x_n$, and how does that, together with the uniform convexity imply $\lVert x_n-x\rVert\to 0$?
Comment: There is no reason why we should have $\lambda(x_n-x)= \lVert x_n-x\rVert$.
Comment: The case $x = 0$ is immediate. So suppose $x\neq 0$. Consider a linear functional $\lambda$ with $\lVert\lambda\rVert = 1$ and $\lambda(x) = \lVert x\rVert$.
Comment: @Daniel Fischer:  do you mean $\Vert \lambda(x) \Vert = \Vert x \Vert$?  $\lambda(x) = \Vert x \Vert$ is not linear, or do I miss something?
Comment: See Theorem 11.8 [here](http://books.google.com/books?id=qSyO4LinPAMC&pg=PA116&lpg=PA116&dq=radon+riesz+theorem+uniformly+convex&source=bl&ots=WEQHpwmwGB&sig=7KU-tYrRTGO0_CFvqd3-aeNNaTk&hl=en&sa=X&ei=UF-nU8jeEaejsQTdioDoBw&ved=0CDYQ6AEwBA#v=onepage&q=radon%20riesz%20theorem%20uniformly%20convex&f=false).
Comment: I think λ(x)=∥x∥ since $X$ is a reflexive Banach space, is it true?
Comment: @Daniel Fischer, I can not prove by considering λ(x)=∥x∥ please help me
Comment: since $x_n\stackrel{w}\to x$ so we have $\lambda(x_n -x)=||x_n- x||$ hence $||x_n-x||\to 0$. Is it true?
Comment: @Daniel Fischer:  OK, thanks for clarifying.
Comment: @DanielFischer, may be you should write an answer?
Answer: The case $x = 0$ is immediate, since $\lVert x_n\rVert\to 0$ is just the norm convergence of $(x_n)$ to $0$.
So let's suppose $x\neq 0$, and, without loss of generality, $\lVert x\rVert = 1$. By the Hahn-Banach theorem, there is a continuous linear functional $\lambda$ with $\lVert\lambda\rVert = 1$ and $\lambda(x) = 1$.
Since $x_n \xrightarrow{w} x$, we have $\lambda(x_n) \to \lambda(x) = 1$, and therefore
$$\lim_{n\to\infty} \lambda\left(\tfrac{1}{2}(x_n+x)\right) = 1,$$
which implies
$$\liminf_{n\to\infty} \left\lVert \tfrac{1}{2}(x_n+x)\right\rVert \geqslant 1.$$
On the other hand, since $\left\lVert\frac{1}{2}(x_n+x)\right\rVert \leqslant \frac{1}{2}(\lVert x_n\rVert + \lVert x\rVert)$, we have
$$\limsup_{n\to\infty} \left\lVert \tfrac{1}{2}(x_n+x)\right\rVert \leqslant 1,$$
so
$$\lim_{n\to\infty} \left\lVert\tfrac{1}{2}(x_n+x)\right\rVert = 1.$$
But a space is uniformly convex if and only if for all sequences $(a_n)$ and $(b_n)$ with $\lim\limits_{n\to\infty} \lVert a_n\rVert = 1 = \lim\limits_{n\to\infty} \lVert b_n\rVert$ and $\lim\limits_{n\to\infty} \left\lVert \frac{1}{2}(a_n+b_n)\right\rVert = 1$ it follows that $\lim\limits_{n\to\infty} \lVert a_n - b_n\rVert = 0$.
Pick $a_n = x_n$ and $b_n = x$.
This characterisation of uniform convexity may be part of the definition, or be a lemma to be proved. In that case, we only need one direction here:
Suppose $\lVert a_n - b_n\rVert \not\to 0$. Then there is an $\varepsilon > 0$ such that $\lVert a_{n_k} - b_{n_k}\rVert > 2\varepsilon$ for subsequences $(a_{n_k})$ and $(b_{n_k})$. We may assume that this holds for the full sequences. For that $\varepsilon$, by uniform convexity, there is a $\delta > 0$ such that
$$\left\lVert \tfrac{1}{2}(u+v)\right\rVert \leqslant 1 - \delta$$
for all $u,v$ with $\lVert u\rVert = 1 = \lVert v\rVert$ and $\lVert u-v\rVert \geqslant \varepsilon$.
Then, setting $\alpha_n = \frac{1}{\lVert a_n\rVert}a_n$ and $\beta_n = \frac{1}{\lVert b_n\rVert}b_n$ ($a_n = 0$ or $b_n = 0$ can happen only finitely often, we drop these terms), we have
$$\begin{align}
\left\lVert\alpha_n-\beta_n\right\rVert &\geqslant \lVert a_n-b_n\rVert - \lVert a_n-\alpha_n\rVert - \lVert b_n-\beta_n\rVert\\
&= \lVert a_n-b_n\rVert - \lvert 1 - \lVert a_n\rVert\rvert - \lvert 1-\lVert b_n\rVert\rvert\\
&> 2\varepsilon - \lvert 1 - \lVert a_n\rVert\rvert - \lvert 1-\lVert b_n\rVert\rvert\\
&> \varepsilon
\end{align}$$
for $n$ so large that $\lvert 1-\lVert a_n\rVert\rvert < \varepsilon/2$ and $\lvert 1-\lVert b_n\rVert\rvert < \varepsilon/2$. But then
$$\begin{align}
\left\lVert \tfrac{1}{2}(a_n+b_n)\right\rVert
&\leqslant \left\lVert \tfrac{1}{2}(\alpha_n+\beta_n)\right\rVert +
\tfrac{1}{2}(\lVert \alpha_n - a_n\rVert + \lVert \beta_n-b_n\rVert)\\
&\leqslant 1-\delta + \tfrac{1}{2}(\lVert \alpha_n - a_n\rVert + \lVert \beta_n-b_n\rVert)\\
&\leqslant 1 - \frac{\delta}{2}
\end{align}$$
for $n$ so large that also $\lvert 1-\lVert a_n\rVert\rvert < \delta/2$ and $\lvert 1-\lVert b_n\rVert\rvert < \delta/2$, contradicting the assumption $\left\lVert \frac{1}{2}(a_n+b_n)\right\rVert \to 1$.

Summary: In a uniformly convex space, the curvature of spheres is "sufficiently large" in all directions that the intersection of a spherical shell $a-\varepsilon < \lVert y\rVert < a+\varepsilon$ with a "thickened supporting hyperplane" $a-\varepsilon < \operatorname{Re} \lambda(y) < a+\varepsilon$ becomes arbitrarily small as $\varepsilon \to 0$.
Comment: That follows from $\lambda\bigl(\tfrac{1}{2}(x_n + x)\bigr) \to 1$ and $\lVert\lambda\rVert = 1$. By that we have $$1 - \varepsilon \leqslant \bigl\lvert \lambda\bigl(\tfrac{1}{2}(x_n + x)\bigr)\bigr\rvert \leqslant \lVert \tfrac{1}{2}(x_n+x)\rVert$$ for all sufficiently large $n$, whatever $\varepsilon > 0$ is given.
Comment: I hate to comment on old answers but could you explain how you got that $\liminf\|\frac{1}{2}(x_n+x)\|\geq1$ ? Did you use continuity somehow?


Multivariate regressions with qualitative features

Question: In the example from An Introduction to Statistical Learning Book about interpretations of coefficients in existence and regression with quantitative and qualitative variables (Example south, east and west region) in chapter 3, topic 3.3. It is said that there must always be the number of levels -1 as dummy variables with the interpretation of the coefficients being
yi = β0 +β1 xi1 +β2 xi2 +ϵi
β0 +β1 +ϵi > if south
β0 +β2 +ϵi > if west
β0 +ϵi > if east
But if 3 dummy variables (β1, β2, β3) were created for the three levels, would the interpretation be wrong not considering one of the levels as a baseline? I ask why it is said that "there must always be one less dummy variable than the number of levels. The level without dummy being the baseline" and I always see dummy with all levels.
And when there is more than one categorical variable with more than two levels, what should the baseline β0 be?
Answer: The number of dummy variables must be 1 less than the number of categories. This helps to avoid the "Dummy Variable Trap", which is a fancy way of saying "to avoid perfect multicollinearity". If you include all categories as dummies, you can perfectly predict one category from the other, causing multicollinearity.
So, we treat any one category as a baseline and predict the other categories with the help of their coefficients.
Suppose, you have two categorical variables of Gender (male/female) and Region (north/south). Your equation could look something like this:
Y = B1 + B2(Gender) + B3(Region) + e
where, Gender = {1 = female; 0 = male} and Region = {1 = north; 0 = south}
In this example,

your baseline "B1" = male from south.
B1 + B2 = female from south
B1 + B3 = male from north
B1 + B2 + B3 = female from north
Comment: The process can be extended. Suppose you also have to include a dummy for West and East in regions. You can simply include 2 more variables where, "Region1 = {1=East; 0=south}" and "Region2 = {1=West; 0=south}". Your baseline stays the same (male from south), but you get 2 more coefficients B4 and B5 for East and West. As an example, B1+B2+B4 = female from east
Comment: How create this baseline when two categorical features have +2 levels ?


Need help with Least Squares Estimator

Question: I am interested in a One-Way ANOVA model:

I wrote the model out as  and got $X$ as a matrix that looks like:

Which is rank 2 (6 x 4 Matrix, so not full rank)
Does the least squares estimator for β = (µ, α1, α2)^T
exist? If it exists, is it unique? Why?
Comment: I see three parameters ($\alpha_1, \alpha_2,\mu$) in your model but four columns in $X.$  *What does that extra column represent??*
Answer: Here is a hint for your self-study question:
Is the design matrix full rank?  Also, please add the self-study tag.  What do you know about full-rank vs. non-full rank matrices and the estimability of the parameters?
Also, have you tried fitting a model with a full rank design matrix and one without a full rank design matrix in your statistical software program?  Some programs will generate a helpful warning that might help you answer this question.

Need help with Least Squares Estimator


Is this a function and injective/surjective question

Question:
Consider the set $A={(x^2, x):x \in R}$. Is this a function from $R$ to $R$?

I know it will be a function if there is a unique output per input, but I've never seen a function formatted like this. Is the $x^2$ the independent value and $x$ the dependent?

A function $f:Z \rightarrow Z x Z$ is defined as $f(n) = (2n, n+3)$. Verify whether this function is injective and whether it is surjective.

Here I'm confused how to prove either injective and surjective. I can't see an $n$ such that I get the same output making it not injective, thus I think it's injective...but not sure how to show it.
I don't think it's surjective because $f(n)$ does not map to $(1, 0)$ for example. But if something were surjective how would I prove it? Thanks for any help!
Comment: A function $f:A\to B$ is "really" a subset $f$ of $A\times B$ with the following property: for each $x\in A$ *there is one* and *only one* $y\in B$ such that $(x,y)\in f$.
Answer: For your first question, suppose that we had two elements of $A$ with the same coordinate: that is, we had $(a, b) \in A$ and $(a, c) \in A$. Then by definition of $A$, we have that $b^2 = a = c^2$, so $b^2 = c^2$. So does it follow that $b = c$? (It doesn't.)
For the second, you are correct that it is injective: For if $f(n) = f(m)$, then $$(2n, n + 3) = (2m, m + 3) \implies n + 3 = m + 3 \implies n = m$$ You're also correct that it's not onto, since it never hits $(1, 0)$. If it were onto, then you'd select an arbitrary element of $\Bbb{Z} \times \Bbb{Z}$ and find an element of $\Bbb{Z}$ mapping to it.
Answer: This is a relation  between the square real numbers and the real numbers. Each square real number $x^2\to x $, Notice that $9\to 3$ and $9\to -3$.  Therefore, this cannot be a function.


Help proving a problem about an even (in the functional sense) marginal distribution

Question: Let $X$ have density function $f$ and let $Y = X$ with probability $0.5$ and $Y = -X$ with probability $0.5$. Show that $Y$ is symmetric about $0$, that is $f_Y(y) = f_Y(-y)$.
What I don't understand is how this is even possible considering that $Y=X$ and $Y=-X$ are two lines in the $x,y$ plane, the area of the joint distribution function over this domain should be relatively small ?
Comment: Compute the cumulative distribution function of $Y$ in terms of that of $X$. You will be able to show it is differentiable; you can compute its derivative $f_Y$ in terms of $f$; and it will then be obvious that $f_Y$ is symmetric. (Using the CDF avoids any technical difficulties surrounding the singular nature of the *joint* distribution of $(X,Y)$.)
Comment: Self study ;) ? Can you start writing the density of $f_Y$
Comment: Please add the `[self-study]` tag & read its
[wiki](http://stats.stackexchange.com/tags/self-study/info). Then tell us
what you understand thus far, what you've tried & where you're stuck. We'll
provide hints to help you get unstuck. Please make these changes as just
posting your homework & hoping someone will do it for you is grounds for closing.
Comment: I never asked for the answer first of all, I specifically said I am having trouble understanding (from a visual perspective) how this could exist
Comment: I see your point. The area is, in fact, zero. But, roughly speaking, it is not a "joint density per square unit" anyway. I think that [this question](http://stats.stackexchange.com/q/91045/22228) is getting at the same issue as yours.
Comment: What is the probability (density) that $Y=5$.
Answer: Hint: Given any real function $g(x)$ defined on all $\mathbb R$,
$h(x) = \displaystyle \frac{g(x)+g(-x)}{2}$ is an even function, that is,
$h(y) = h(-y)$ for all $y \in \mathbb R$.


The RTL css file is not working for a menu

Question: I wanted to make the CorporateClean theme RTL. Every thing is Ok except Main Menu. It effects alignment for both languages. For Persian is also right and for English as well.
As example: I wrote the following code in RTL Css file
<code>#header-menu ul.menu li {
float:right;
dir:rtl;
text-align:right;
}
</code>
It makes the menu RTL for both English  and Persian languages.
Answer: you mistake is here     dir:rtl; :(, and correct code will be below "dadash"
<code>#header-menu ul.menu li {
float:right;
direction:rtl;
text-align:right;
}
</code>
Comment: Actually I use this code direction:rtl; and exactly the code you wrote above.But the problem is that my site reads the style-rtl.css before style.css.
Comment: @jkahmadi so it can happened because of very reasons !!!, if you sure that style.css load after style-rtl.css  exchange them :D , Check the `.info` file and be sure `stylesheets[all][] = css/style-rtl.css` is after `stylesheets[all][] = css/style.css`


What is a good website monitoring service/program for monitoring side-projects?

Question: I know this is a frequently-discussed topic, but I've read multiple other questions and haven't found anything relevant. I want a website uptime monitoring service or software for my side-projects, so cost is a primary factor.
My requirements are:

Free for ~10ish sites.
Frequent HTTP uptime checks (15 seconds to a minute between checks).
Nice UI.
Email alerts.

I haven't managed to find a service like this, but I don't mind setting up an open-source service. However, my requirements there are:

Lightweight in RAM/CPU usage.
Easy to set up (would ideally only need me to run one process).
Few dependencies (ideally only an SQLite database).
Basic web UI (just showing a graph, I don't even need web configuration).

Anything I've seen fails at least one of the above criteria, usually the processes and dependencies ones. Most packages (Nagios, Munin, Zabbix, etc) seem to be enterprise-grade with full monitoring, but I just want a simple thing that will email me when one of my projects is down.
Is there something like that, or should I write one?
Comment: Why is this question closed? Sigh, this is where I see StackExchanged being usurped by Quora.
Answer: There are actually many offers available out there.
Besides most of them propose a minimum of 1min uptime check, there is several free tools.
Here's a comparative list of many products (paid+free), you might find what suits best for you.
https://www.keycdn.com/blog/website-monitoring-tools/
I would personaly consider Monitority a good solution for your needs.
Good search!
Comment: Thank you, that list has many sites I'd never seen before. UptimeRobot looks good, although they only have 5-minute checks. Thanks again!
Comment: Uptime Robot supports 1-minute checks in the Pro Plan -disclaimer: I'm a part of the Uptime Robot team :)-.


Affect the text click to a checkbox in Reactjs

Question: How to affect a text click to a checkbox? Now it works as when we click on a checkbox it is selected, I want to select it while I'm clicking on the corresponding text also. Here my code,

            <input type='radio' id={taskList.ID} name={'ID: ' + taskList.ID} onClick={_onclick} checked={selected} />
            {taskList.Priority}

Comment: Possible duplicate of [How to create a checkbox with a clickable label?](https://stackoverflow.com/questions/6293588/how-to-create-a-checkbox-with-a-clickable-label)
Answer: Try wrapping your text into label element like below.

   <input type='radio' id={taskList.ID} name={'ID: ' + taskList.ID} onClick={_onclick} checked={selected} />

  {taskList.Priority}


Accuracy values are missing while applying KNN on Iris data using caret package in R

Question: Something is wrong; all the Accuracy metric values are missing:
getting this error while applying k-nn on iris data.
''' iris.knn<- iris
# Dividing data into test_train
set.seed(532)
sample.iris.knn <- sample.split(iris.knn, SplitRatio = 0.8)
train.iris.knn <- subset(iris.knn, sample.iris.knn== TRUE)
test.iris.knn <- subset(iris.knn, sample.iris.knn == FALSE)
dim(train.iris.knn)
str(train.iris.knn)
head(train.iris.knn)
# fitting K-nn model
set.seed(8237)
trControl.iris.knn <- trainControl(method = "repeatedcv",
                                    number = 10,
                                    repeats = 3)

iris.knn.model <- train(Species ~., data = train.iris.knn,
                        method = 'knn',
                        trainControl = trControl.iris.knn,
                        preProcess = c("center", "scale"),
                        tuneLength = 13)
# Model check
iris.knn.model

'''
Answer: There is no argument in the function train named trainControl , it is trControl so change it will solve your problem
iris.knn.model <- train(Species ~., data = train.iris.knn,
                        method = 'knn',
                        trControl = trControl.iris.knn,
                        preProcess = c("center", "scale"),
                        tuneLength = 13)


Isomorphic 2-graphs

Question: Two graphs
Can we say that these two graphs are isomorphic? I think no because $\deg^-(c) \ne \deg^-(g)$. The solution says they are isomorphic, but I don't understand why. Am I wrong?
Comment: Please don't change your question to a completely different question. If you do that, then the answer I wrote for your original question makes no sense, and I worked hard writing that answer :(
Comment: Why did you change the graphs in your prompt? If you have questions on another problem with different graphs, you should either expand this post or open a new one, but not rewrite this one. Also, you should leave in your initial ideas to solve the problem, not delete them.
Comment: What solution? In a textbook? In some class lecture? You aren't saying. Surely whatever source you're reading defined isomorphism before giving you a problem on isomorphisms. Undirected graph isomorphisms are a one-to-one correspondence between vertices that also creates a one-to-one correspondence between edges. For directed graphs, such a correspondence needs to preserve the orientation of edges.
Comment: "They say [the graphs] are isomorphic" - wait, but who is "they"? Anyway, the undirected versions of these graphs are isomorphic, but not the directed versions.
Comment: @runway44 The solution says it is isomorphics. Can you explain why? What kind of isomorphism is that?
Answer: Both you and the solution are wrong.
Just saying that $\deg^-(c) \ne \deg^-(g)$ doesn't mean anything, because $c$ doesn't have to be paired with $g$. An isomorphism of these two directed graphs would be a function $$\phi : \{a, b, c, d\} \to \{e, f, g, h\}$$ that preserves directed edges. Checking that $\deg^-(c) \ne \deg^-(g)$ tells you that we cannot have $\phi(c) = g$ in any isomorphism. However, we have $\deg^-(c) = \deg^-(f)$, so we can't immediately rule out that there's an isomorphism $\phi$ with $\phi(c) = f$.
What we can say by looking at indegrees and outdegrees is that any isomorphism must have:

$\phi(a) = h$, because these are the only vertices with outdegree $2$ and indegree $0$;
$\phi(b) = g$, because these are the only vertices with outdegree $0$ and indegree $2$;
either $\phi(c) = e$ and $\phi(d) = f$, or $\phi(c) = f$ and $\phi(d) = e$.

Possibly the solution telling you that the graphs are isomorphic made the mistake of only checking the degrees.
However, once we've figured out the above, we immediately know that there can't be an isomorphism, because there is an edge $(h,g)$ but no edge $(a,b)$.

Isomorphic 2-graphs


Diffeomorhism of manifold

Question:
This is one of the exam questions of the previous semester. I have studied these. But I didn't do this. Please show me how to solve this question. Thank you for help
Comment: Think level sets.
Comment: Yes, I guess the same theorem you said. But how do I apply level set theorem to here? Please show me the application? @ShaunAult
Answer: Consider the functions $$\phi\colon\mathbb{R}^{n-1}\to f^{-1}(0)\colon (x^1,\ldots,x^{n-1})\mapsto(x^1,\ldots,x^{n-1},F(x^1,\ldots,x^{n-1}))$$
and
$$\psi\colon f^{-1}(0)\to\mathbb{R}^{n-1}\colon(x^1,\ldots,x^n)\mapsto(x^1,\ldots,x^{n-1}).$$
$\psi$ and $\phi$ are both clearly differentiable and $\psi\circ\phi$ is clearly the identity.
Now consider $(\phi\circ\psi)(x^1,\ldots,x^n) = (x^1,\ldots,x^{n-1},F(x^1,\ldots,x^{n-1}))$. Since $(x^1,\ldots,x^n)\in f^{-1}(0)$, we have $0=f(x^1,\ldots,x^n) = F(x^1,\ldots,x^{n-1})-x^n$, hence $x^n=F(x^1,\ldots,x^{n-1})$ and $(\phi\circ\psi)(x^1,\ldots,x^n)=(x^1,\ldots,x^n)$.
Thus, indeed $f^{-1}(0)$ is diffeomorphic to $\mathbb{R}^{n-1}$ as a manifold. This also immediately implies that $f^{-1}(0)$ is in fact a manifold.
Comment: You help me so much during the day. Thank you so @Abel :) you solve explanatorily so I have understood easily and well. :)
Answer: Define a diffeomorphism $h:R^n\rightarrow R^n$ by $h(x^1,\dots,x^n)=(x^1,\dots,x^{n-1},f(x^1,\dots,x^n))$. Then $f^{-1}(0)$ is mapped to $R^{n-1}=\lbrace (x^1,\dots,x^n)\in R^n|x^n=0 \rbrace\subset R^n$ which is a submanifold. Hence $f^{-1}(0)$ is a manifold with a smooth structure induced by $h$ (and $h$ is defined by $f$) and diffeomorphic to $R^{n-1}$.

Diffeomorhism of manifold


O365 Hybrid and Sophos Email Appliance

Question: I am planning to migrate our Exchange 2010 SP3 server to O365 using Hybrid environment.
We also use Sophos Email Appliance which is a box sitting inhouse.
Currently, the mail flows like this.
Inbound from Internet
Internet --> Sophos Email Appliance --> Edge Server --> Mail Server

Outbound to Internet
Mail Server --> Edge Server --> Internet
I want to retain Sophos Email Appliance and at the same time don't want to break the Microsoft rule that I should not be putting anything between O365 and On-Premises Exchange and also referring to the following article:
https://docs.microsoft.com/en-us/exchange/mail-flow-best-practices/manage-mail-flow-on-office-365-and-on-prem
I come up with:
Inbound from Internet
Internet --> Sophos Email Appliance --> O365 --> Edge Server --> Mail Server
(I must admit the routing is a bit inefficient as incoming mail has to be sent back to the internet to reach O365)

Outbound to Internet (no change)
Mail Server --> Edge Server --> Internet
Will this work?
Thanks in advance.
Answer: Yes, as we know, Microsoft does not support any third-party SMTP gateways between EOP and the on-premises hybrid connectors; the only supported device is an Exchange Edge Transport server. While you can leave your non-hybrid traffic routing through a third-party appliance, using it in the middle of your hybrid mail flow may cause messages to appear as external and is not supported.
We could refer to the following documents:
https://docs.microsoft.com/en-us/exchange/mail-flow-best-practices/manage-mail-flow-on-office-365-and-on-prem
https://docs.microsoft.com/en-us/exchange/edge-transport-servers

I think it will work.
Comment: How about this issue?

O365 Hybrid and Sophos Email Appliance


ORA-00904: Invalid identifier - Creating a simple table

Question: I'm trying to create a simple table, but I'm receiving error:

ORA-00904 - invalid identifier

and I'm not sure why.  I don't see anything that could be causing the issue (using Oracle 11g Express):
CREATE TABLE Measurements(
  MeasureAmountID       SMALLINT        PRIMARY KEY,
  MeasurementDescription    VARCHAR(255),
);

Answer: Remove the comma at the end and try,
CREATE TABLE Measurements(
     MeasureAmountID     SMALLINT PRIMARY KEY,
     MeasurementDescription  VARCHAR(255)
     );


"Topological disjoint union" vs "disjoint union"

Question: I want to understand the definition of topological disjoint union. Let $X$ be a topological space such that we can write $X=\bigsqcup X_i$. We say that $X$ is the "topological disjoint union" of the $X_i$ if each $X_i$ is an open subset of $X$, but if the $X_i$ are not necesserily open subsets of $X$ we say that $X$ is a the "disjoint union" of the $X_i$ only as sets (without the topological adjective) which means that $X =\cup X_i$ is the union of the $X_i$ such that all the $X_i$ are pairwise disjoint as sets. Is my understanding correct? thank you for your help!
Answer: Yes, you are correct. But sometimes the adjective "topological" is implied as you are working in the category of topological spaces. One can make the distinction also by saying "disjoint union of subspaces" vs. "disjoint union of subsets". It really depends on the context how careful one has to be to distinguish the two situations.
I would also like to add that there two versions of the sum / disjoint union. One of them is a construction – you start with any family of sets/spaces, and then you construct their sum. For this you often have to replace the original spaces by isomorphic copies that are disjoint. The other one is a property – you already have the whole space and a family of its subspaces, and you ask whether the whole space is the sum of those subspaces. Of course the two variants are closely connected – the latter propery holds if and only if the given space is canonically isomorphic to the constructed one. Also note that this phenomenon is not special to topological spaces and sets, it happens for example with the direct sum of modules / vector spaces.
Comment: @palio: Because it is not. The fact that the subsets are also open means that they are clopen. The subspaces do not interact in any way, they are totally separated. It also correspond to being a coproduct in the sense of category theory.
Comment: I'm talking  in the category of topological spaces not the category of sets and i'm distinguishing the case of open vs "non open" subsets $X_i$. so we say the disjoint union is topological  only when the subsets are open, but when the subsets $X_i$ are not open in $X$ we say it is a disjoint union. For example if $X$ is locally connected, $X$ is the topological disjoint union of its connected components, but if $X$ is not locally connected, we say that $X$ is a disjoint union of its connected components, is that correct ?
Comment: In wikipedia it is said: "It follows that a locally connected space $X$ is a topological disjoint union ${\displaystyle \coprod C_{x}}$ of its distinct connected components."
Comment: @palio Yes, that is correct. Note that for components, it is disjoint union of closed sets in general.
Comment: Is there a reason behind reserving the word topological to the case when the subsets are open? I mean why we don't say a space (not necessarily locally connected) is a topological disjoint union of  its connected components?
Answer: A topological space is a pair $(X,T)$ where $T$ is a topology on the set $X,$ but it is common to call it "the space $X$" when a particular $T$ is assumed.
If $(X_i,T_i)$ is a topological space for each $i\in I$ then the topological sum (topological disjoint union) is $(X, T)$ where $X=\cup_{i\in I} X_i\times \{i\}$ and $T$ is the topology on $X$ generated by the base (basis) $\cup_{i\in I}\{t\times \{i\}: t\in T_i\}.$


Google Cloud Pub/Sub Emulator Deadline Excedeed

Question: Recently my pubsub-emulator from google cloud ( https://cloud.google.com/pubsub/docs/emulator?hl=pt-br ) started hanging and not creating any topic, and when i do manage to publish a message in a existing topic, it either hangs and gives me DEADLINE_EXCEEDED or it takes a looong time to go...
Some more data: It started happening recently, here are my versions
Ubuntu 22.04
Google Cloud SDK 417.0.1
alpha 2023.02.08
beta 2023.02.08
bq 2.0.84
bundled-python3-unix 3.9.16
core 2023.02.08
gcloud-crc32c 1.0.0
gke-gcloud-auth-plugin 0.4.0
gsutil 5.19
pubsub-emulator 0.7.4
From my teammates, only Me and another co-worker are getting this behavior as well
I Already tried reinstalling my ubuntu, but it kept behaving like this...
Any lights or directions? I'm lost
Answer: Recently, I had a communication problem between the emulator and the python commands for creating topics and subscriptions in this guide. The error returned was "google.api_core.exceptions.DeadlineExceeded: 504 Deadline Exceeded". I solved the problem by setting the --host-port parameter with the value localhost:{somePort} on starting the emulator. When I don't configure this parameter, the emulator sets the host ::1 and the example commands don't work.