Need help understanding Bernoulli standard deviation

Question: I'm looking at the solution of a homework problem from a class I took many years ago and I'm not understanding how they calculated standard deviation (see question 1C here:  http://datasciencelabs.github.io/2016/pages/html/hw2-problems.html).  In the roulette game, a player wins a dollar with a probability of 18/38, and loses a dollar with a probability of 20/38, the solution to 1C says that the standard deviation is:
|1 --1|*sqrt((9/19) * (10/19))
Where does the |1 --1| come from?  I recognize the rest of the formula as sqrt(p*(1-p)) which I believe is the standard deviation of the Bernoulli distribution (please correct me if I am wrong).
Answer: At Problem 2E on that link is the formula $|a-b|\sqrt{p(1-p)}$, which is the standard deviation when you win $a$ with probability $p$ and $b$ with probability $(1-p)$. If you're asking about the vertical bars, that's the absolute value; the difference  between winning and losing. You have the case with $a=1$ and $b=-1$
As you suggest, the second half is the Bernoulli standard deviation. In a Bernoulli distribution you get 1 success with probability $p$ and 0 with probability $1-p$, so the term out the front is $|1-0|$.  If you win 1 or lose 1 (ie,  win $-1$), the difference between winning and losing is  2 rather than just  1, so the standard deviation is  the  Bernoulli standard deviation multiplied by 2.


How to create a node based on views results

Question: I'm looking for a way to accomplish the following:
Use views to select users that match a certain criteria.
Create a "campaign" targeted at only those users. The campaign should ideally have all users' names/ids attached to it.
Many thanks.
Answer: I think you need 2 relationships in Views. One that targets your field that points from user to the campaing. Second, with the author, based on the first relationship.
After, add as fields user names.
Not really sure about your structure so that was just a supposition.


$2^4 = 4^2$ are there any other solutions to $x^y = y^x$?

Question: How would I go about solving $x^y = y^x$?
$$\frac{y}{\ln y} = \frac{x}{\ln x} $$
Is trivial to find, but I'm not sure where I'd go from here.
Thanks in advance
Comment: http://mathforum.org/library/drmath/view/67256.html never mind.
I was looking for integer solutions
Comment: Dear @FrancisTP, I think it would be quite alright to post the contents of that link as an answer yourself and accept the answer.
Comment: Are you after integer solutions? Or real solutions?
Comment: Try drawing a plot of $f(x) = \frac{x}{log(x)}$
Comment: Of course, there is always the pair $(x,y)=(1.1)$.
Comment: Any $x=y$ except $0$ is a solution as well.  That is all in the integers.
Comment: But the only non-trivial integer pair is $(2/4)$, but there are more rational non-trivial solutions.
Comment: [This question](https://math.stackexchange.com/questions/2013607/find-all-positive-integers-such-that-xy-yx?noredirect=1&lq=1) is related
Answer: The plot of $\frac{\ln x}{x}$ looks so:

By searching for the solutions of $\frac{x}{\ln x} = \frac{y}{ln y}$ where $x \ne y$, you are looking for the points of this plot with the same $y$-coordinate.
As you can see, $2^4 = 4^2$ is your only integer solution.
Answer: Plotting (using Geogebra) $\frac{x}{\log_{10}(x)}=\frac{y}{\log_{10}(y)}$ gives

As we can see, the only integral solutions are $(2,4)$ and $(4,2)$ (as well as the trivial $(x,x) \in \Bbb{Z} \times \Bbb{Z}$ solutions). This is because as $y$ (respectively $x$) increases, the curve asymptotes to an $x$ coordinate of $>1$ (respectively $y$ coordinate of $>1$) but never reaches it.
Comment: Don't forget the solution -2, -4.
Answer: The only integer solution is (2,4).
You are solving
$$y^x=x^y$$
and if you fix $y$, you (almost) always have two solutions for $x$. One is $x=y$, the other is not expressible in closed form with "traditional"  functions, but you can use the transcendental function $W(z)$, the Lambert function, which solves
$$xe^x=z \mapsto x=W(z)$$
To do this, you transform the equation into
$$e^{x\ln y}x^{-y}=1$$
$$x e^{(-x\ln y/y)}=1$$
$$(-x\ln y/y) e^{(-x\ln y/y)}=-\ln y/y$$
The parenthesised expression can be your unknown, arriving at
$$-\frac{x\ln y}{y}=W(-\ln y/y)$$
$$x=-\frac{y}{\ln y}W(-\ln y/y)$$
Provided you have a way to compute $W$, this gives you a solution.
Special case: for $y=e$, the only (double) solution is $x=y=e$. This is the crossover point: for $y<e$, the nontrivial solution is $x>e$ and vice-versa.


Integrability of indicator of $f(x) \geq 0$ for a continuous function f.

Question: Let $f(x)$ be some continuous function of $x$, and
$$
g(x) =
\begin{cases}
1 & \text{when }f(x) \geq 0\\
0 & \text{otherwise}
\end{cases}.
$$

Is $g(x)$ Lebesgue integrable over any finite interval $[a, b]$?
Also, is it Riemann integrable over $[a, b]$?

If not, is there a natural set of conditions on the class of continuous functions for which it is integrable?
Comment: The set $\{x\mid f(x)>0\}$ is open by continuity, so thus it is measurable, which implies $g$ is measurable. However, it isn't necessarily integrable.
Comment: You have to define the domain you are integrating over for this to have a meaningful answer.
Comment: The answer to your question to @Alan is no. The set of discontinuities of $g$ can have positive measure.
Comment: How about $f(x)=x$?
Comment: @Alan Is the following argument correct?
 $g(x)$ can have at most countably many points of discontinuities since $f(x)$ is continuous. So $g(x)$ is continuous almost everywhere, which implies that it is integrable.
Comment: Domain is any finite interval. I also made an edit to the question to clarify this.
Comment: What is the domain of $f$?
Comment: The title says $\{f>0\}$ and the actual question says $\{f\ge 0\}.$ Which is it?
Comment: @zwh I was really confused, trying to figure out what my question was there.  IT was actually from the OP who just tagged me :).
Comment: (1) You seem to be asking at least three different questions here (about Lebesgue integrability, Riemann integrability, and the integrability of continuous functions).  Please try to ask only one question at a time. (2) Your question is lacking context.  Please edit your question to explain what you know, what definitions might be helpful (e.g. the definitions of Riemann and Lebesgue integrability), and any thoughts you might have on the problem.
Comment: I have refunded your bounty, so that you can make improvements to your question(s) without encouraging answers to respond to a half-formed question, or a question which might change while you fix the problems identified above.
Answer: I'll assume $f$ is continuous on $[a,b].$ Let $E=\{x:f(x)\ge 0\}$ and $g=\chi_E.$
Is $g$ Lebesgue integrable on $[a,b]?$ Yes. Proof: Because $f$ is continuous, $f^{-1}(A)$ is closed for any closed set $A.$ Therefore $E =f^{-1}([0,\infty))$ is closed, and hence measurable. Therefore $\chi_E$ is measurable. A bounded measurable function is always Lebesgue integrable on a set of finite measure. Since $[a,b]$ has finite measure, $g$ is Lebesgue integrable on $[a,b].$
Is $g$ Riemann integrable (RI)? Not always. Let $U$ be an open subset of $[a,b]$ containing the rationals in $[a,b],$ such that $0<m(U)<b-a.$ Let $E=[a,b]\setminus U.$ Then $E$ is closed, nowhere dense, with $m(E)>0.$
Define $f(x)=-d(x,E).$ Then $f$ is continuous on $[a,b]$ with $f<0$ on $U$ and $f=0$ on $E.$ Thus $E=\{x:f(x)\ge 0\},$ which is what we want. Claim: $g=\chi_E$ is discontinuous at each point of $E.$ To prove this, note that if $x\in E,$ there is a sequence of rationals converging to $x.$ Along this sequence we have $g=0$ whereas $g(x)=1.$ This proves the claim and shows $g$ is not RI by Lebesgue's criterion.
At the end you ask if there are natural conditions on the class of continuous functions for which $g$ is integrable.  Since $g$ is always Lebesgue integrable, I'll take this as a question about RI. In fact there are $C^\infty$ functions such that the corresponding functions $g$ are not RI. The proof is a fancier version of what we did above. Let $U,E$ be exactly what we did above. Then there exists $f\in C^\infty[a,b]$ such that $f=0$ on $E$ and $f<0$ on $U.$ Then we get the same result: $g=\chi_E$ fails to be RI by Lebesgue's criterion.
Here's a condition that gives a positive result: If $f$ is real analytic on $[a,b],$ then the corresponding $g$ is RI. That's because the zero set of $f$ is either everything, or just a finite set. It follows that $E$ is a finite disjoint union of closed subintervals of $[a,b],$ from which the RI of $g=\chi_E$ follows easily.


If my master zone is not named "master" should my client zones.conf contain the zone "master"?

Question: My Icinga2 master zone (parent zone of all my other zones) is named "core" so I'm wondering whether the zones.conf files on my Icinga2 client machines should ever contain references to "master."
Here's an example of a client zone.conf file.
<code>object Endpoint "mon-prod.polywog.net" {
        host = "191.120.289.30"
        port = "5665"
}

object Zone "master" {
        endpoints = [ "mon-prod.polywog.net" ]
}

object Zone "global-templates" {
  global = true
}

object Endpoint NodeName {
}

object Zone ZoneName {
        endpoints = [ NodeName ]
        parent = "master"
}
</code>
Answer: Whatever your root zone name is, use that instead of "master." The 'icinga2 node wizard' is not able to update config files very well. It does not reliably update constants.conf either.


Easy little geometry prob

Question: If a chord divides a circle into parts with areas in ratio 5:7, what is the angle between a tangent line to the circle at one of the ends of the chord and the chord?
(1) 15° (2) 75° (3) 90° (4) 115°.
I tried using sines theorem and drawing the centered triangles out, but I'm not sure how to figure out the angle out.
Comment: I don't think any of those answers are right.
Comment: @OP: can you clarify the problem? Are we told that the circular sector $AOB$ has $\frac{5}{12}$ the area of the circle or that the (smaller) area cut off by the cord has $\frac{5}{12}$ the area of the circle?
Comment: @KimJongUn It's the segments, which complement each other to the circle
Comment: @JackiePoehler. Thanks.
Answer: If you only need to quickly find a solution without any strict proof.
Intuition. It can't be $>90°$ since the angle between two lines by definition $\leq 90°$. Also it can not be $90°$ since this is the diameter case. $15°$ correspond to very small chord. So the only residual choice is $75°$.
Comment: Good intuition but $75^0$ is also NOT an answer. See @aschepler 's comment.
Answer: Let $\theta$ the central angle of the circular segment whose area is $\frac{5}{12}$ of the circle. The desired angle is the half of $\theta$.
So find out $\theta$ using:
$$\frac{r^2}{2}(\theta- \sin\theta)=\frac{5}{12}\pi r^2$$
You will get:
$$\theta=2.878 \text{rad},$$
or
$$\theta =164.9^\circ{}.$$
Therefore the angle is $82.45^\circ{}$.
Answer: Let $ a$ be the diameter of circle touching y-axis at the origin.
$\psi$ is the required angle and so on basis of $\psi$, all areas are computed.
$ \dfrac{\sin(\psi)} {r} = \dfrac{1}{a} $ ...(1*)
$ \psi^ {'} = \dfrac{1}{a} $...(2*)
Curvature $ k_g = \sin (\psi)/ r + \psi^{'} = 1/a + 1/a =2/a $...(3*)
where primes are with respect to arc length.
$ \dfrac{dA}{d\psi} = \dfrac{r^2}{2} \dfrac{d\theta}{ds} \dfrac{ ds}{d\psi} $ ...(4*)
$ A = \int_\psi ^{\pi/2} \sin^2(\psi)* a^2/2 * d\psi $..(5*)
$ a^2/2 * ( \pi/4 -( \psi/2 - \sin(2 \psi)/4 ) = \pi (a/2)^2 *\frac{1}{12} $...(6*)
Remaining area fraction is $ \frac{1}{12}$ because portions $ \frac{5}{12}$ is situated above and $ \frac{1}{2}$ in semi-circle below.
The equation numerically solves to $ \psi =82.4566 $ degrees, an option not among those given.

Easy little geometry prob


Administer Users permission too vague. How can I restrict functionality for this permission?

Question: Is there a way to allow some admin users (with administer role) to create other users but limit their access to 'people' related admin area? It seems there's only one option under permissions - Administer users - which seems to dictate either full package (create all different profile2 users, access admin people list view etc) or nothing.
I have a 'sales person' role on the system. This user has to be able to create other profile2 based users but not to access user configuration or even general listing (not to mention that depending on number of profile2 profiles, multiple Add People links appear)
Answer: I believe the Role Delegation module does what you need to do. Here is a quote about it (from the module's project page):

... allows site administrators to grant some roles the authority to assign selected roles to users, without them needing the administer permissions permission.
For each role, Role Delegation provides a new assign ROLE role permission to allow the assignment of that role.
The module also adds an assign all roles permission. Enabling this permission for a role is a convenient way to allow the assignment of any other role without having to check all the assign ROLE role permissions in the Permissions page.
If an administrator has the administer users permission, a role assignment widget gets displayed in the account creation or editing form, and bulk add/remove role operations become available on the user administration page. Otherwise, if s/he has at least the access user profiles permission, the module adds its own Roles tab to the user profile so that roles can be assigned.
Comment: It's not what I need actually. This module seems to deal with roles assignment. I want to be able to allow a specific user role to create other users (essentially just access this url admin/people/p2rp-create/user). And only this. Everything else, admin user view, other Add People links (as there could be a few depending on number of profile2 entities), user configuration has to be disabled


What trigger menu_rebuild flag in semaphore table?

Question: Well, this question appear to be simple, but my problem is a little bit more complex. I'll try to explain my situation.
I have a site with customized template and a bunch of modules (all 3rd party from Drupal contrib site). When any content needs to be updated, which means include, update or delete a node, page or panel causes a slow down in entire site. The site practically stops. For everyone (anonymous and logged users).
I began an investigation and I realized that menu_rebuild flag in semaphore table is taking too long (~5 minutes) to disappear. This is causing trouble for every user who wants to  navigate on the website, because menu_rebuild is locking down the site.
One side effect of this menu_rebuild lock is the queue of apache processes in the server. This leads the server to be overloaded (100% CPU).
My conclusion after this investigation is simple. Something (a module maybe) is firing the menu_rebuild many times causing the site lockup. I tracked down the function in Drupal core that activate menu_rebuild. See:
includes/menu.inc
/**
 * Populates the database tables used by various menu functions.
 *
 * This function will clear and populate the {menu_router} table, add entries
 * to {menu_links} for new router items, and then remove stale items from
 * {menu_links}. If called from update.php or install.php, it will also
 * schedule a call to itself on the first real page load from
 * menu_execute_active_handler(), because the maintenance page environment
 * is different and leaves stale data in the menu tables.
 *
 * @return
 *   TRUE if the menu was rebuilt, FALSE if another thread was rebuilding
 *   in parallel and the current thread just waited for completion.
 */
function menu_rebuild() {

  if (!lock_acquire('menu_rebuild')) {
    // Wait for another request that is already doing this work.
    // We choose to block here since otherwise the router item may not
    // be available in menu_execute_active_handler() resulting in a 404.
    lock_wait('menu_rebuild');
    return FALSE;
  }

  $transaction = db_transaction();

  try {
    list($menu, $masks) = menu_router_build();
    _menu_router_save($menu, $masks);
    _menu_navigation_links_rebuild($menu);
    // Clear the menu, page and block caches.
    menu_cache_clear_all();
    _menu_clear_page_cache();

    if (defined('MAINTENANCE_MODE')) {
      variable_set('menu_rebuild_needed', TRUE);
    }
    else {
      variable_del('menu_rebuild_needed');
    }
  }
  catch (Exception $e) {
    $transaction->rollback();
    watchdog_exception('menu', $e);
  }

  lock_release('menu_rebuild');

 return TRUE;
}

When I comment the lock_wait('menu_rebuild'); / lock_release('menu_rebuild'); calls, my site runs smoothly and fast. But I can't do that. This affects the generation of new content.
I disabled all modules that I could without breaking the template. If you need to know what modules that I have installed, please ask.
I am using Drupal 7.23. My server configuration:

Ubuntu 12.04 LTS
4 cores / 8GB RAM
Apache 2.2.22;
PHP 5.3.10 / FastCGI;

If you need information about apache configuration or PHP configuration, please let me know.
Update:
Here are all active modules in my site:
[CORE]

Block
Contact
Content translation
Contextual links
Dashboard;
Field;
Field SQL Storage;
Field UI;
File
Filter;
Image;
List;
Locale;
Menu;
Node;
Number;
Options;
Overlay;
Path;
RDF;
Shortcut;
System;
Taxonomy;
Text;
Toolbar;
Update Manager;
User;

[FIELDS]

Entity Reference;
Link;
Select(or other);

[ACCESS CONTROL]

ACL;

[SPAM CONTROL]

CAPTCHA;
Image CAPTCHA;

[DATE/HOUR]

Date;
Date API;
Date Popup;
Date Views;

[EMAIL]

Newsletter;
SMTP Authentication Support

[USER INTERFACE]

CKEditor;
Options element;
Pagestyle;

[META TAGS (QUICK)]

Meta tags (quick);

[LOCALIZATION]

Localization update;

[INTERNATIONALIZATION]

Block languages;
Contact translation;
Field translation;
Internationalization
Menu translation;
Multilingual contant;
Multilingual select;
Path translation;
String translation;
Synchronize translations
Taxonomy translation;
Translation redirect;
Translation sets;
Variable translation;

[MEDIA]

File entity;
IMCE;
IMCE Mkdir;
Media

[OTHERS]

Entity API;
Pathauto;
Profile2;
Profile2 pages;
Token;
Transliteration;
Vocabulary Permissions Per Role;

[PANELS]

Panels;

[SUITE CHAOS TOOLS]

Chaos tools;
Page manager;
Views content panes;

[VARIABLE]

Variable;
Variable realm;
Variable store;
Variable views;

[VIEWS]

Embed Views Display;
Views;
Views UI;

[WEBFORM]

Webform;
Webform validation;

[WEBFORM DYNAMIC SELECT]

Webform options;

[WORKBENCH]

Workbench;
Workbench access;
Workbench Media;
Workbench Profile;

[XML SITEMAP]

XML sitemap;
XML sitemap engines;
XML sitemap internationalization;
XML sitemap menu;
XML sitemap node;
XML sitemap taxonomy;
Comment: Can you provide a list of the modules?
Comment: You could throw a `watchdog('menu_rebuild', '' . print_r(debug_backtrace(), TRUE) . '');` into the menu_rebuild function, that should show all the routes into it in the watchdog log
Comment: preferably mark those you already have disabled when you provide the list of modules.
Comment: @Steven, I updated my question with all enabled modules.
Comment: @arpitr, I didn't put the disabled modules. Do you need it?
Comment: No not disabled modules, but the thing that Clive wrote would also help.
Comment: And just to double check, those modules are ALL enabled right?
Comment: @Steven, yes. The modules listes are all enabled.
Comment: @Clive, using your hint, I found something. When I call the front page, the menu_rebuild() is triggered, and what is wrote in watchdog is HUGE (~1MB of data)! Looking to this information, I also found the function `block_page_build` with more than 3000 arrays inside. `[args] => Array` (>~3000).
Comment: Ouch that's a lot of data. Try using something like [this](http://www.php.net/manual/en/function.debug-backtrace.php#112238) to get a meaningful trace of the function calls
Comment: Yah run a backtrace on it and maybe post the results in here. `block_page_build` should not have more then 3000 arrays lol. It should have a bunch but you probably don't have a 100 blocks on your page.
Comment: I disabled the block module (core) and the site works much faster. But, the most of the content has gone without blocks. The template has 59 regions defined and the site have ~1 block  for each region. Next step I'll run the backtrace.
Comment: Well, I pasted the content of debug of the menu_rebuild function to watchdog. Take a look: http://tny.cz/b5aaca3f
Comment: Well, the problem is the template. We hired a supplier to develop a template for our company. Badly coded. Thanks for your help guys. If the supplier resolve this problema, I will update this question. Tks again.
Answer: After a long wait, we finally figured out what is the real problem. This can be splitted in two parts: the custom template that we use and the Chaos Tools Module.

The template was really bad coded. Had functions accessing the database all the time and making unnecessary I/O. We refactored the template;
Chaos Tools is a really nice module, but it really slow down my site. Not all Chaos Tools, but specifically the Page Manager. I don't know why, but there is a loop in file /sites/all/modules/ctools/page_manager/page_manager.module causing all the trouble when I was trying to save a new page, for example. This loop trigger menu_rebuild semaphore and the page manager take an eternity to remove this flag from semaphore table.

Open the file page_manager.module and scroll down to line ~148
// And for those that provide subtasks, provide menu items for them, as well.
foreach (page_manager_get_task_subtasks($task) as $subtask_id => $subtask) {
   // Allow the task to add its own menu items.
   if ($function = ctools_plugin_get_function($task, 'hook menu')) {
      $function($items, $subtask);
   }
}

I commented this entire loop to solve this problem. I don't know all the impact this action can cause to my site, but now, when I save a new content, the speed increased and the menu_rebuild is not triggered.
// And for those that provide subtasks, provide menu items for them, as well.
// foreach (page_manager_get_task_subtasks($task) as $subtask_id => $subtask) {
//   Allow the task to add its own menu items.
//   if ($function = ctools_plugin_get_function($task, 'hook menu')) {
//      $function($items, $subtask);
//   }
// }

I believe this is not a bug on Chaos Tools, but maybe this can be improved.
Comment: My server's usage was insanely high. I reached this page via http://serverfault.com/questions/541604/apache-consuming-too-much-cpu-and-memory#comment679567_561065 and your suggestion seems to work! What do you mean when you say "menu_rebuild flag in semaphore table is taking too long (~5 minutes) to disappear"? Haven't used Drupal since a long time
Comment: Most probably the problem is not your server. Just make sure it is configured right. I don't know much about `menu_rebuild_flag`. All I know is this `menu_rebuild_flag` is used by some Drupal functions and modules too. However, this is not a problem at all when used with caution. This flag can lock the site if it was active. If some module need to lock to do some routine, the module can trigger this flag. To check the flag on yout database, just do: `select * from semaphore`
Answer: To figure out an issue like this, you should enable XHProf, which is a tool that will profile your CPU (and memory) usage and will show you how the trace of calls through the system that calls this function.  From that you can find out what module or section of code that is causing the issue.
There is a great page documenting how to set up Drupal and XHProf, and let us and the module owners know what you find.
Comment: Thanks for your reply! But, after a long wait, we figured out that the problem was the template and Chaos Tools. I explain better on my answer.


CDetailView don't show properly Chtml::link's HTML data

Question: i use Chtml::link in one CDetailView.
array(
                    'label'=>'Images',
                    'type'=>'html',
                    'value'=> CHtml::link('','#',array('data-target'=>'#myModal','class'=>'tag','data-toggle'=>'modal')),
                ),

But html properly not generated. it only add few property like below

How can i add all property?
Answer: array(
  'label'=>'Images',
  'type'=>'html',
  'value'=> CHtml::link('','#',array('data-target'=>'#myModal','class'=>'tag','data-toggle'=>'modal')),
),

change 'type'=>'html',       to
       'type'=>'raw',
After changing the code its look like below block
array (
  'label' => 'Images',
  'type'  => 'raw',
  'value' => CHtml::link('','#',array('data-target'=>'#myModal','class'=>'tag','data-toggle'=>'modal')),
),


Chrome Console and Javascript Object Type

Question: I would like to find the type of a Javascipt object (the name of the constructor function) but I keep just getting a generic "Object" back with all methods I have tried. I have searched online and no Javascript method I have found has work for me yet. It always just returns the object constructor type as a generic "Object". Yet there it is, staring right at me when I inspect it in the Chrome console. Any ideas how I might get that information in JS?
PS. I am using Browserify's require to separate my code if that make a difference.

The reason I thought it might be because of how Browserify loads require code is because this is the output I get from a Browserify loaded constructor function:

And here is what I get from creating a constructor function manually:

Regardless of that and regardless of how I create my constructor function var Prey = function() {} vs var Prey = function Prey() {} the Chrome dev tools still seem to know what the name of the constructor function was even when Javascript does not seem to know. Perhaps this is because they can inspect the code in the virtual machine in a way the the Javascript language does not have access to but I am wondering if I am missing something. Does anyone know of another way to determine an instance type in Javascript?
Comment: Please show how that object is constructed.
Comment: It seems like that whatever constructed `obj` didn't set the `constructor` property properly.
Comment: @thefourtheye added more information on the constructor functions. Hope that provides better context. Thanks!
Answer: The Prey you are seeing is the Prey when you do function Prey(){};, thus, the function name is Prey. If you define Prey as var Prey = function(){}; then the function name is "";
So basically if you want use the function name, you must give your constructor a name. var Prey = function Prey(){};
EDIT: or its possible that you did a variation of this:
var A = function NAMED(){};
var B = function(){};
B.prototype = Object.create(A.prototype);
var o = new B();

> o
 o.constructor.name
< "NAMED"

Comment: Does that explain why obj.constructor.name is "Object" though?
Comment: But then it wouldn't show up as Prey... Even if you set the prototype manually via `obj.__proto__ = Prey.prototype` it will set both the constructor name and the console display.


Assess if 2 groups are different given control variables

Question: Say I have 2 groups of people, selected randomly. For each person, I know some characteristics about them, in the form of continuous and categorical variables. For example, that could be the person's weight (continuous integers), whether they smoked or not (binary variable), number of 10 min+ walks per week (1, 2, 3, 4+) etc...
At this point, I am interested in deciding wether the 2 groups look identical, according to my control variables stated above.
I know I can compare the 2 groups for each variable. I could perform a t-test on the group's weight distributions. I could run a chi-squared test when the variables are categorical.
I would like an overall test that will, at the end, give me one p-value describing the difference between the 2 groups and decide if I can consider them significantly different or not.
Does such a test exist? If not, how would you tackle this problem?
Answer: If the purpose of this exercise is to assess balance for the purposes of comparing groups in an observational study, you shouldn't be using hypothesis tests to do so. This is commonly referred to as the "balance test fallacy". In a balance test, you only care about assessing whether the groups in your sample differ from each other. See Imai, King, & Stuart (2008) and Ho, Imai, King, & Stuart (2007) for a discussion.
If you are truly interested in making an inference about the population from which your sample was drawn, what you probably want is a multivariate t-test (MANOVA), or the logistic regression approach could work as well. One problem with the logistic regression approach is that it tests for conditional associations between each variable and the grouping variable, when you actually want marginal associations. The MANOVA makes some assumptions about normality.
Comment: Hello Noah, thanks for the reply.
So far, I have used the Hotelling's T squared method and it seems that according to your comment, it was appropriate. According to this PDF: http://ibgwww.colorado.edu/~carey/p7291dir/handouts/manova1.pdf
"MANOVA is the multivariate analogue to Hotelling's T2". in my case, I have only 2 groups, so Hotelling T square test would be appropriate.
Cheers!
Answer: At first, when there is random selection, then it is not needed to perform such tests.
In cases, where there is a reason to think, that selection was not random, but possibly the populations do not differ in features, we might build a selection model. First choice would be logit with group as dependent variable. Testing for significance of whole model would give the right answer, as long you have chosen good variables.
It is actually necessary to have one test for all the comparisons, because we avoid multiple comparison problem this way.
To perform joint test for significance of all variables in logit model, first-choice test would be Likelihood-Ratio test. Some statistic software does it automatically, when you estimate the model. One can thing of this test as equivalent of the F test for OLS regression.
Comment: Hello @cure, thanks for the reply.
The model would be something of the form y = f(categorical or continuous variables) where y takes the value Group_1 or Group_2. I would train on the data that I already have. Once the model is trained, I can test for the significance of the parameters. However, you are mentioning the significance of the whole model. Is there a particular procedure you would follow? Or Do you have a link/example you could share? Thanks!
Comment: Hello @Damien, I added paragraph suggesting a joint test for logistic regression model. If you looking for procedure to estimate such model, at first you need to choose software (you probably have already using one). Then I think you should just go through some tutorials for logistic regression using such soft. I hope this would be enough to perform such thing!
Comment: Sounds good, thanks for the suggestions! I will have a look. So far, I have tried the Hotelling T square distribution, which seems to do the trick, but I still have to look more into it.


Jquery & PHP not directing to header function

Question: I have this simple login form with Jquery, ajax & PHP when the login is successful the home page is showing in div section instead of going to a next webpage. Any suggestions?
HTML Form:

<form method="post" class="form-horizontal" action="login.php">
    <input id="userid" name="userid" type="text" class="form-control" placeholder="User ID">
    <input id="password" name="password" type="password" class="form-control" placeholder="Password">
    <button type="submit" name="submit" id="submit" class="btn btn-primary">Login</button>

</form>

PHP code:
<?php
include 'db.php';

$user = $_POST['userid'];
$pass = $_POST['password'];

$query = mysqli_query($con, "SELECT * FROM login WHERE userid='$user' AND password='$pass'") or die (mysqli_error($con));
$result = mysqli_num_rows($query);

while($row = mysqli_fetch_array($query)){
  $_SESSION['user'] = $row['userid'];
}

if(!$result){
  echo "Username or Password is incorrect!";
}else{
  header("Location: claims.php?id='".$_SESSION['id']."'");
}
mysqli_close($con);
?>

Comment: You can not redirect the _front end_, by responding to a _background request_ with a redirect. That response "lands" in your JavaScript code.
Comment: Does this answer your question? [How to manage a redirect request after a jQuery Ajax call](https://stackoverflow.com/questions/199099/how-to-manage-a-redirect-request-after-a-jquery-ajax-call)
Comment: can you tell me the workaround?
Answer: I have found the answer is to redirect with Javascript
echo '';


Prove or disprove that H is a subgroup

Question:
Let $H= \{a+bi:a,b \in \mathbb{R}, ab \geq 0\}.$ Prove or disprove that $H$ is a subgroup of $\mathbb{C}$ under addition.

I know to show that $H$ is a subgroup of $\mathbb{C}$ it has to show that:

$H \neq \emptyset$.
$H$ is closed.
$H$ has an inverse.

Since $a,b \in \mathbb{R}$, then we can clearly see that
$H \neq \emptyset$.
Suppose $x$, $y \in H$ then $x= a_1+b_1i$ and $y=a_2+b_2i$ then $x+y \rightarrow a_1+b_1i+a_2+b_2i$ am I taking this on the right direction?
To find the inverse then $x^-1=(a+bi)^{-1} = (bi)^-1+(a)^{-1}=  (a)^{-1}+(bi)^{-1} $since $\mathbb{C}$ is abelian.

This is the approach I took.
Answer: $$\begin{array}{rcl}
3+4i &\in& H \\
-4-3i &\in& H \\
(3+4i)+(-4-3i)=-1+i &\notin& H \\
\end{array}$$

There are three fatal flaws in your attempt:

You didn't actually prove that $x+y \in H$. You just computed $x+y$ which is a complex number, but this doesn't mean it is in $H$.
This is a group under addition. Your choice of $\cdot^{-1}$ makes it look like you are considering the multiplicative inverse, when actually the inverse of $a+bi$ is $-a-bi$. I'm not sure if you actually know this.
Again, you haven't proved that the inverse is again in $H$.
Comment: can you explain how you got the $-4-3i \in H$?
Comment: @Killercamin $(-4)(-3) = 12 \ge 0$
Comment: Oh i see, so i was going on the right direction but forgot to add values?
Comment: what do you mean?
Comment: isn't your example that h is not closed, so my "proof" to show that is closed is wrong. right?
Comment: @Killercamin I've edited my answer to argue why your proof is wrong.

Prove or disprove that H is a subgroup


Building a ln function from scratch

Question: I need to write a natural logarithm with just limited available operations.
This is to be implemented as a function into a C program. The problem is, our product is security relevant so the source code has to be well documented and tested.
The testing process is why we are writing all code from scratch, as the C standard librarys are not well documented and writing our own tests for it that cover the whole library would take longer as just developing what we need our self.
Long story short:
I reviewed some opensource math librarys and just encoutnered for every ln()-function/method a quite big source with some nested dependencies to other even biger math-functions.
double log(double x)
{
    int e;
    double y, z;
    /* Test for domain */
    if( x <= 0.0 )
        return 0;

    /* separate mantissa from exponent */
    /* Note, frexp is used so that denormal numbers
     * will be handled properly.
     */
    x = frexp( x, &e );
    /* logarithm using log(x) = z + z**3 P(z)/Q(z),
     * where z = 2(x-1)/x+1)
     */

    if( (e > 2) || (e < -2) )
    {
        if( x < SQRTH )
        { /* 2( 2x-1 )/( 2x+1 ) */
            e -= 1;
            z = x - 0.5;
            y = 0.5 * z + 0.5;
        }
        else
        { /*  2 (x-1)/(x+1)   */
            z = x - 0.5;
            z -= 0.5;
            y = 0.5 * x  + 0.5;
        }

        x = z / y;
        /* rational form */
        z = x*x;
        z = x * ( z * polevl( z, R, 2 ) / p1evl( z, S, 3 ) );
        y = e;
        z = z - y * 2.121944400546905827679e-4;
        z = z + x;
        z = z + e * 0.693359375;
        goto ldone;
    }
    /* logarithm using log(1+x) = x - .5x**2 + x**3 P(x)/Q(x) */

    if( x < SQRTH )
    {
        e -= 1;
        x = ldexp( x, 1 ) - 1.0; /*  2x - 1  */
    }
    else
    {
        x = x - 1.0;
    }
    /* rational form */
    z = x*x;
    y = x * ( z * polevl( x, P, 5 ) / p1evl( x, Q, 5 ) );

    if( e )
        y = y - e * 2.121944400546905827679e-4;
    y = y - ldexp( z, -1 );   /*  y - 0.5 * z  */
    z = x + y;
    if( e )
        z = z + e * 0.693359375;

ldone:

    return( z );
}

This is code was allready hardened by me. But it is still depending on 4 other math functions (ldexp, polevl, p1evl and frexp) which I would have to implement my self aswell.
My math knowledge is allready overstrained with this code, so I couldn't verify even this is working correctly after I trimmed the code not mentioning implementing the additional implementations or the moment I had to document and jsutify the tests.
So why I'm asking here and not on StackOverflow:
I want to know, are there any easyer implementations or approximation procedures to determine the ln in a not that complex way, so I don't have to waste alot of resources for studying the maths behind?
Answer: For functions such as $\log$ from a standard library, I think it would be a mistake to reimplement them from scratch in the hope that your own implementation would be somehow "better". The standard implementations have been optimized for speed and accuracy for several decades, and it's unlikely that you can improve on it unless you are a highly specialized expert both in numerical analysis and the relevant hardware architecture.
That said, there are other libraries that are in some sense better, for example returning values that are guaranteed to be correctly rounded. For example, you might be interested in crlibm

Added: If you you want something simpler, and can live with a limited range of allowed input values, you can for example find a rational approximation of $\log x$. For example, computing the "(3,3) Padé approximation" of $\log x$ around $x=1$ gives:
$$
\log x \approx \frac{\frac{11}{60}(x-1)^3 + (x-1)^2 + (x-1)}{-\frac12 + \frac32 x + \frac 35(x-1)^2 + \frac1{20}(x-1)^3}
$$
giving reasonable accuracy, at least on the interval $[0.5, 4]$. Here is a graph of the two functions

and a graph of the quotient (showing relative accuracy)
Comment: I don't want to improve them, I can even live with a decent fallback in accuracee and performance isn't the problem either, but the problem is that our product gets approved for the market requires that each line of code (means also the functions invoked) is documented and tested. So the options are: build the math stuff from scratch and proof that the tests of them are justifing. or use the function of some one else and proof that its tests are justifing. So it woudl be more easy to write an own `log` as proofing some one else `log` works flawless, wouldn't it?
Comment: What kind of proofs are you looking for? Verifcation of correctness? Possible security flaws? Something else? The crlibm I liked to are verifyably correct.
Comment: so In other words, I'm looking for a simplification of a `log` while I can accept a certain inaccuracy
Comment: It's really hard to understand why your (most likely  inferior) implementation would be preferable. To me it seems like testing (in the computer science sense) of a *mathematical* function is to make sure that the function is accurate (and not crashing on any input). Again, the library I linked satisfies those criteria.
Comment: I'm not completly aware of the kind of proof. But it is the advice of my boss that we don't use external sources because that would simply waste resources in the testing phase. so even if I would get convinced that doesn't change the fact that I have to write it.
Comment: I'll have a look on it. and if you could include to your answer reasons about, why there is no way of simplifing this, I had at least an argument why this job shouldn't be done a) this way or b) by me.
Comment: If you want a simplified approach, it can probably be done. **But** you need a good specification: What kinds (ranges) of inputs should be acceptable? What accuracy is necessary? And so on. Otherwise, what would your own testing test?
Comment: the possible input would be real numbers from 0 to round about 2 going higher could happen but that could be waved away as the system would have other problems in that case to worry about.
Comment: Its worth noting that, for this kind of approach, the first step is it multiply/divide the input by e until its in the range 1/sqrt(e) < x < sqrt(e), and then use the formula. Each multiply/divide will add/subtract one from the output, which you will need to account for.
Answer: I had to implement logarithms on rational numbers.
This is how I did it:
Occording to Wikipedia, there is the Halley-Newton approximation method

which can be  used.
Using Newton's method, the iteration simplifies to (implementation), which has cubic convergence to ln(x).
// Using Newton's method, the iteration simplifies to (implementation)
// which has cubic convergence to ln(x).
public static double ln(double x, double epsilon)
{
    double yn = x - 1.0d; // using the first term of the taylor series as initial-value
    double yn1 = yn;

    do
    {
        yn = yn1;
        yn1 = yn + 2 * (x - System.Math.Exp(yn)) / (x + System.Math.Exp(yn));
    } while (System.Math.Abs(yn - yn1) > epsilon);

    return yn1;
}

This is not C, but C#, but I'm sure anybody capable to program in C will be able to deduce the C-Code from that.
Forthermore, since

logn(x) = ln(x)/ln(n).

You have therefore just implemented logN as well.
public static double log(double x, double n, double epsilon)
{
    return ln(x, epsilon) / ln(n, epsilon);
}

where epsilon (error) is the minimum precision.
Now as to speed, you're probably better of using the ln-cast-in-hardware, but as I said, I used this as a base to implement logarithms on a rational numbers class.
Arbitrary precision might be more important than speed, under certain circumstances.
Then, use the logarithmic identities for rational numbers:
logB(x/y) = logB(x) - logB(y)
Comment: This looks like a good way to improve on an initial estimate, that estimate coming from a Taylor series/Pade approximation.
Comment: @Eddy: The Taylor series approach is not efficient since the convergence is slow.
This is using Newton's method, which has cubic convergence to ln(x).
Comment: Yes, but what's your value of $y_0$? Im simply recommending, for example, $y_0=x-1$ using the first term of the taylor series.
Comment: @Eddy: Ah, well, then - a better start value - yes, why not.

Building a ln function from scratch


Construct a bijective monotone function whose inverse is not monotone

Question: The reason of this question is an exercise in category theory:

Find a counterexample to the following statement: A monotone function $f:X\longrightarrow Y$ between posets $X$ and $Y$ which is a bijection on the underlying sets (an isomorphism in $\mathcal{S}et$) is necessarily an isomorphism in $\mathcal{P}arset$.

In short, this exercise asks me to give a bijective monotone function whose inverse is not monotone.
In this link: Are monotonic and bijective functions the same? the accepted answer gives an example that $f(x)$ is bijective but not monotone. I tried to define $f^{-1}(y)$ as the same as $f(x)$ defined in this post, and compute the $f$. Then we can have $f^{-1}(y)$ not monotone and $f$ bijective.
However, the problem is after the computation, I found that $f$ has the same expression as $f^{-1}$ in the same regions, which implies that $f$ is not monotone.
I also tried different constructions using linear function, it turned out that we can easily arrive either both $f$ and $f^{-1}$ are monotone or neither of them is monotone.
Is there any other possible construction I can follows?
By the way, in all the attempts I made, the construction is on $X=(\mathbb{R},\leq)$ and $Y=(\mathbb{R},\leq)$, so it is perhaps easier to choose other partially ordered set, for instance $Y:=(2^{\mathbb{R}},\subset)$, but then I don't know how to construct a bijective monotone function at all...(overall in the category theory, the monotone function can be respect to different partial orders, for instance, $x_{1}\leq_{X} x_{2}$ implies $f(x_{1})\leq_{Y} f(x_{2})$.)
Thank you!
Answer: Consider $X=Y=\{0,1\}$ with $ x \preceq_X y$ if and only if $x=y$ and $x \preceq_Y y$ if and only if $0 \preceq_Y 1$ or $x=y$.
The identity is a monotonic bijection between $(X,\preceq_X)$ and $(Y,\preceq_Y)$. However, the inverse is not monotonic.


Solid Region of Infinitely Many Type-I Regions

Question: Find a solid region in $\mathbb{R}^3$ which can be written as disjoint union of countably infinitely many type-I regions, but cannot be written as disjoint union of finitely many type-I regions. If such region does not exist, prove it.
Type-I regions are defined as:  region where $u_{1}(x,y)\le z \le u_{2}(x,y)$
and where $(x,y)$ are in $D$, which spans the $xy$-plane.
Comment: What are $u_1, u_2?$  What is $D?$
Comment: Welcome to math.SE. For some basic information about writing math at this site see e.g. [here](http://meta.math.stackexchange.com/questions/5020/). Please, try to make the title of your question more informative.
Answer: The $u_{1}(x,y)$ and $u_{2}(x,y)$ represent two continuous functions.  From Stewart Calculus 7th edition on page 1018:
"A solid region $E$ is said to be of type 1 if it lies between the graphs of two continuous functions of $x$ and $y$, that is,
$$E= \big\{ (x,y,z) \; | \;(x,y) \in D, \; u_{1}(x,y) ≤ z ≤ u_{2}(x,y) \big \} $$
where $D$ is the projection of $E$ onto the $xy$-plane."


Find the inverse of this function.

Question: Let define the function
$$f(x)=(a+b)\frac{16(\pi+x)x}{5\pi^2+4(\pi+x)x}-b\frac{(\pi^2-4x^2)x}{\pi^2+x^2}$$
for $x \in [\frac{-\pi}{2},0]$ such that $a,b \in \mathbb{R}$ and  $0<a<b$.
What is the inverse of $f$ on $[\frac{-\pi}{2},0]$ ?
I tried to calculate it several times but I did not succeed.
Comment: Where did this problem come from? Was it inspired by [this answer](https://math.stackexchange.com/a/3768808/1508)?
Comment: @TonyK  this is a modified question from this question https://socratic.org/questions/5a08c0da7c0149261b6c1130 by taking the  Mahabhaskariya of Bhaskara  approxiamtion
Comment: @MoonEstrella. The extra $x$ at the end of the equation makes a problem. Are you sure about it ?
Answer: This is not an answer.
This is amazing since, for $-\frac \pi 2 <x<0$,
$$\frac{16(\pi+x)x}{5\pi^2+4(\pi+x)x} \sim \sin(x)$$
$$\frac{(\pi^2-4x^2)}{\pi^2+x^2}\sim \cos(x)$$ These approximations are $1,400$ years old.
If the problem was (I removed the last $x$)
$$f(x)=(a+b)\frac{16(\pi+x)x}{5\pi^2+4(\pi+x)x}-b\frac{(\pi^2-4x^2)}{\pi^2+x^2}$$ then an approximation would be
$$f(x)=(a+b) \sin(x)-b \cos(x)$$ which is a basic trigonometric equation.
Comment: Claude you are too old for me (+1) for the wisdom

Find the inverse of this function.


How do I implement back button support on a form in Wicket?

Question: I have a search page with a tabbed panel, with a form within each tab (see code below), that when submitted searches the database for hits. However, back button support on this form is not working (user supplied text in textField is lost). How do I implement back button support for this form? I have been playing around with issuing setVersioned(true) on the page, panel, form and textField in combination with modelChanging() and modelChanged() on the textField and the form, but none of those have worked. I have also tried overriding method newLink from TabbedPanel as detailed here, but that has not worked either. I'm at a loss...
Any help would be greatly appreciated.
public class TextSearchPanel extends Panel {
    CompoundsDataTablePanel hitsPanel;

    @SpringBean
    ICompoundDAO            compoundDAO;

    public TextSearchPanel(final String id, final FeedbackPanelWrapper feedbackPanel) {
        super(id);
        setOutputMarkupId(true);

        // Text Search Form
        Form<TextSearchPanel> textform = new Form<TextSearchPanel>("textForm");

        // Add textField
        TextField<String> textField = new TextField<String>("query", new Model<String>());
        textField.setRequired(true);
        textField.add(new StringValidator() {
            @Override
            protected void onValidate(final IValidatable<String> validatable) {
                String query = Name.replaceApostropheVariantsWithApostrophe(validatable.getValue());
                try {
                    // Ascertain parsing query does not throw an exception
                    compoundDAO.parseQuery(query);
                }
                catch (ParseException e) {
                    // Otherwise: Display the error back to the user
                    validatable.error(new ValidationError().setMessage(e.getMessage()));
                }
            }
        });
        textform.add(textField);

        // Add submit button
        textform.add(new IndicatingAjaxButton("ajaxsubmit") {
            @Override
            protected void onSubmit(final AjaxRequestTarget target, final Form<?> form) {
                target.addComponent(feedbackPanel);
                // Show hits panel
                hitsPanel.setVisible(true);
                target.addComponent(TextSearchPanel.this);
            }

            @Override
            protected void onError(final AjaxRequestTarget target, final Form<?> form) {
                target.addComponent(feedbackPanel);
                // Hide hits panel
                hitsPanel.setVisible(false);
                target.addComponent(TextSearchPanel.this);
            }
        });
        add(textform);

        // Text Hits Panel
        hitsPanel = new CompoundsDataTablePanel("hits", new TextHitsProvider(textField.getModel()));
        hitsPanel.setVisible(false);
        add(hitsPanel);
    }
}

Page class:
public class SearchPage extends BasePage {
public SearchPage() {
    super("Search");
    setOutputMarkupId(true);

    List<ITab> tabs = new ArrayList<ITab>();
    tabs.add(new AbstractTab(new Model<String>("Spectrum search")) {
        @Override
        public Panel getPanel(final String panelId) {
            return new SpectrumSearchPanel(panelId, getFeedbackPanelWrapper());
        }
    });
    tabs.add(new AbstractTab(new Model<String>("Mass search")) {
        @Override
        public Panel getPanel(final String panelId) {
            return new MassSearchPanel(panelId, getFeedbackPanelWrapper());
        }
    });
    tabs.add(new AbstractTab(new Model<String>("Formula search")) {
        @Override
        public Panel getPanel(final String panelId) {
            return new FormulaSearchPanel(panelId, getFeedbackPanelWrapper());
        }
    });
    tabs.add(new AbstractTab(new Model<String>("Text search")) {
        @Override
        public Panel getPanel(final String panelId) {
            return new TextSearchPanel(panelId, getFeedbackPanelWrapper());
        }
    });

    // Add tabs to page to switch between search modes
    add(new TabbedPanel("tabs", tabs));
}
 }

Answer: I haven't had chance to try your code out, but could it be a problem with the use of ajax. The back button is not fully supported with ajax in wicket yet: https://issues.apache.org/jira/browse/WICKET-271. You may want to check the versions of the pages you are viewing when pressing the back button when compared with viewing it the first time.
Comment: Thank you Tnem! Indeed, the problem was in the IndicatingAjaxButton. I replaced this with a regular submit button in html, and added override methods onSubmit and onError to the Form, to regulate when the results Panel is visible. It now works.


Convergence of $\frac{S_{n}}{\sqrt{n\log n}}$

Question: Helo
I need to prove the following statement:
Let $X_{1},X_{2},\ldots,X_{n}$ be $iid$ random variables with density
$$f(x) = \frac{1}{|x|^3}I_{|x|>1}$$
Let $S_{t}=\sum_{i=1}^{n}X_{i}$, show that
$$\frac{S_{n}}{\sqrt{n\log n}}\stackrel{d}{\to}\mathcal{N}(0,1)$$
My take: I have shown that $\mathbb{E}[X]=0$ and that $\mathbb{E}\left[X^{2}\right]$ is not defined, so I cannot use the Central Limit Theorem. Which path shall I take?
Thanks a lot
Answer: First, you may show that the characteristic function of $X_1$ is
$$
\varphi_X(t)=1-t^2(-\ln|t|+O(1)) \quad \text{as}\quad t\to 0.
$$
Then
\begin{align}
\varphi_{\frac{S_n}{\sqrt{n\ln n}}}(t)&=\left(\varphi_X\!\left(\frac{t}{\sqrt{n\ln n}}\right)\right)^n=\left(1-\frac{t^2}{n\ln n}\left(\ln\frac{\sqrt{n\ln n}}{|t|}+O(1)\right)\right)^n \\
&\to e^{-\frac{1}{2}t^2}\quad \text{as}\quad n\to\infty,
\end{align}
which is the characteristic function of $N(0,1)$.
Comment: Thank you very much!


Object Equality in jQuery3+

Question: Sample using jquery3.1: https://jsfiddle.net/pyb10ey9/
comparing  same objects from the two different array in jquery3+ version and it return false. I can't able to find where it is differ.
Comment: I tried that but it return true for  different objects also
Comment: try add `.toString()` as in `var isDataEqual = data1.colors[0].toString() == data.colors[0].toString();`
Answer: The right way of comparing 2 objects using vanilla Javascript, and possibly one of the fastest, is JSON.stringify(). Bear in mind, it was introduced with Javascript 1.7 in 2006 and may not work on somewhat older browsers, as you can see here. But still, over 97% global coverage is pretty safe by my standards.
As you can see in your example, it DOES have to rely on the ordering of the properties.
var data = {
colors: [{
    id: 1,
    color: "red"
  }, {
    color: "green",
    id: 2
  }]
};
var data1 = {
  colors: [{
    id: 1,
    color: "red"
  }, {
    id: 2,
    color: "green"
  }]
};
 var isDataEqual = JSON.stringify(data1.colors[1]) == JSON.stringify(data.colors[1]);
      alert("jquery version : " + jQuery.fn.jquery + "\n" + "isDataEqual : " + isDataEqual);

Working JsFiddle
Very informative research

Object Equality in jQuery3+


How to Invalidate Dojo/Require's Module Cache?

Question: I have a dojo-based module that automates loading a dojo/store/Memory for me, using a bang. It's called like so:
require( [ 'squad_builder/storeBroker!collectionStore' ],
    function( collectionStore )
{
    // use store...
} );

The first require() call loads the store and subsequent ones load the store from a cache.
This works well but I cannot figure out how to invalidate require's internal cache so I can make the next request load the store with fresh data.
Is there anything built into require() to do this or do I need to mess with some internal workings (and if so, where?)
Edit
In the docs it mentions:

Note: the dojo loader includes the nonstandard function require.undef,
  which undefines a module value.

But that method is undefined when I call it. Looking at require() in Firebug with:
for( i in require )
{
    console.log( 'require', i, require[ i ] );
}

require.module has a def() method but not an undef() one.
Edit 2
Require.cache only seems to contain dojo and dijit modules. Where are custom namespaced modules cached?
Comment: May I ask why you chose that plugin design rather than using dojo/store/JsonRest to load fresh data from the server using queries ?
Answer: According to the dojo site, the function is not automatically included in "built" dojo files.  If you look at an uncompressed dojo.js you will see it there.
From:http://dojotoolkit.org/reference-guide/1.9/loader/amd.html

The following table provides a list of options that are leveraged
  within the loader. The first column is the Option/Feature as defined
  within the loader, the second options is whether this is a detected
  feature (via has.add()) or if it is just an option and its default
  value. With "unbuilt" source, all the features and options are
  available. If the loader has been built, then some of these features
  may have been set as staticHasFeatures and not be configurable
  anymore.

Also here it says that you might be able to turn the function back on by adding a line go djconfig
http://dojo-toolkit.33424.n3.nabble.com/require-undef-td3990559.html

dojoConfig = {    has : {
        "dojo-undef-api": true    } }


What are advantages of random forests vs using bagging with other classifiers?

Question: I'm studying Random Forests, but after reviewing the methods I got the following line of reasoning: I feel like the big advantage of random forests happens in the bagging process where nearly uncorrelated predictions are created due to the random features, producing predictions with low variance. On the other hand, this method doesn't require your classification method to be a decision tree.
If other classification algorithms (LDA, QDA, logistic regression, etc) usually perform better than decision trees, why would I choose to use decision trees as my classifier?
Random forests seem a lot more popular than bagging with other classifiers (it even got its own name) but I don't see any particular reason why.
Comment: Random forests are actually usually superior to bagged trees, as, not only is bagging occurring, but random selection of a subset of features at every node is occurring, and, in practice, this reduces the correlation between trees, which improves the effectiveness of the final averaging step.
Comment: Ask yourself: what happens if you apply bagging to ordinary least squares? If you apply the parametric bootstrap, you will see that the center of the bootstrap distribution is just the OLS estimate anyway, so bagging will accomplish nothing but introduce Monte Carlo error. We expect to get something qualitatively *different* from our data when *the underlying estimator is unstable*. So bagging tends to be applied with highly unstable methods (like CART) and not with highly stable methods (like logistic regression or LDA).
Comment: One reason might be ease of interpretation to non-ML savvy outsiders.
Comment: Doesn't the bagging process kills the interpretation? Your 'final' prediction is an average of predictions produced by possibly (and very likely) different trees.
Comment: Yeah good point...I was thinking that decision trees are pretty easy to understand, and it might be easier to jump from there to bagging than starting with a more complicated approach.
Answer: I find this a great question. As mentioned by @guy in the comments section, bagging is more useful when the estimator / training algorithm is highly unstable and, I would add to that, non-linear. OLS or MLE are exact methods, on the same dataset they will always converge to the same solution.
CART on the other hand solves an NP-hard problem via greedy search and will produce different results even on the same dataset. There is a significant added overfitting/variance in CART's predictions and this is what bagging makes use of.
Answer: random selection of feature-subset is used at each node in Random Forest RF which improves  variance by reducing correlation between trees(ie: it uses both features and row data randomly)
While Bagging improves variance by averaging/majority selection of outcome from multiple fully grown trees on variants of training set. It uses Bootstrap with replacement to generate multiple training sets.(only Row data is used here)


Bandwidth Usage

Question: I am not sure if this is the correct forum to be posting to, but I thought someone might be able to help?
I have a client running Zen Garden on their site which was phished not too long ago. Ever since then, his bandwidth usage on the site has hit the roof and I was wondering if anyone know of a solution to this please?
Thanks!
Comment: This is not a forum but a QA site and your question is too much vague
Comment: It's not clear what you are asking. Maybe reword your question to say something like 'How do I measure the bandwidth on my site? I am using the operating system 'X' and the webserver 'foo', if that's what you want to know.
Answer: If the site was compromised, nuke the server and start again. See also:
https://serverfault.com/questions/6159/aftermath-of-hack
https://serverfault.com/questions/tagged/intrusion-cleanup
Comment: Also, remember to add in any security patches/processes that are needed to prevent the same thing happening again.
Answer:
If you determine you've been hacked, take your webserver off the network please. Your server may be serving malware, spamming people, functioning as part of a botnet and serving bad stuff for the bad guys.

If you are using Apache webserver, take a look at some of the other Log modules provided by Apache. These can help you track down if your webserver is doing anything strange. These two sound relevant:
Logging actual bytes sent and received
mod_logio adds in two additional LogFormat fields (%I and %O) that log the actual number of bytes received and sent on the network.
Forensic Logging
mod_log_forensic provides for forensic logging of client requests. Logging is done before and after processing a request, so the forensic log contains two log lines for each request. The forensic logger is very strict with no customizations. It can be an invaluable debugging and security tool.
Answer: If you have access to an upstream router look at the traffic that is making up the bandwidth; it could be anything from an open proxy to file sharing site full of illegal content.
Comment: Or run `tcpdmp`, set up SNMP monitoring from another host (using eg. Cacti), etc.

Bandwidth Usage


How to rerender v-data-table on VueJS 2

Question: I have a v-data-table. On a pop up, I select a few of the columns of the table and combine these values and add them back to the table as a new column.
My problem is, I can't re-render the v-data-table after I clicked my Save button. I tried $forceUpdate but didn't work. What can i use?
Answer: It's pretty weird it doesn't get rerendered automatically. But one solution could be to assign your data an empty array (I assume it's an array) and right after it put:
<code>tabledata = []; // empty your data here
Vue.nextTick(function () {
   tabledata = [0,1,2]; // assign your new data here
})
</code>
https://v2.vuejs.org/v2/api/#Vue-nextTick

How to rerender v-data-table on VueJS 2


Python numpy keep a list of indices of a sorted 2D array

Question: I have a 2D numpy array and I want to create a new 1D array where it is indices of numbers in the first array if they are sorted in an ascending order. For the following array:
A = [[1,0,2],
     [0,3,0]]

I want this to be like:
B = [[1,1],[0,2],[0,0],[0,1],[1,0],[1,2]]

Any idea how it can be done in python using predefined functions?
Thanks
Answer: You can use argsort to sort the indices of flattened array, followed by unravel_index to convert the flat index back to coordinates:
>>> i = (-a).argsort(axis=None, kind='mergesort')
>>> j = np.unravel_index(i, a.shape)
>>> np.vstack(j).T
array([[1, 1],
       [0, 2],
       [0, 0],
       [0, 1],
       [1, 0],
       [1, 2]])

-a and kind='mergesort' is in order to sort the array in a stable manner in descending order (to match the output you are looking for).
If you do not care about having a stable sort, replace the first line with:
>>> i = a.argsort(axis=None)[::-1]

Comment: The tip about using `np.unravel_index` is brilliant!  I am glad to learn this method.
Comment: @stvn66 I believe this does produce consistent sorting for identical values which is equal to stable sorting
Comment: What do you mean by "stable sort"?  Does this produce consistent sorting for identical values?


Por que isso está retornando None?

Question: Estou tendo dificuldades com os ajustes de certas palavras geradas aleatoriamente, mais especificamente, problemas na hora de consestar certas palavras como ziiːno, onde não quero duas letras iguais se encontrem, mas esse é o resultado:
import re

test_word = "ziiːno"
print(re.match(r"(.)\1ː?", test_word))
# None

Isto deveria retornar iiː ou i pelo que fiz no regex101. Alguem sabe o que está acontecendo?
Answer: De acordo com a documentação:

re.match() checks for a match only at the beginning of the string, while re.search() checks for a match anywhere in the string

Ou seja, match faz a busca a partir do início da string. Se quer buscar em qualquer parte da string, use search.
Outro detalhe é que estas funções retornam um objeto Match. Se você quer apenas o texto que a regex pegou, pode pegar o grupo zero do Match (usando [0]), que corresponde a todo o trecho capturado:
import re

test_word = "ziiːno"
print(re.search(r"(.)\1ː?", test_word)[0]) # ii:

Comment: eu jurava que essas duas funcionavam da mesma forma, valeu pela ajuda e por me lembrar de sempre olhar a documentação.

Por que isso está retornando None?


TypeScript: Is there a way to type a function so that it returns different types of results dynamically according to it params

Question: This is a very contrived example so please bear with me:
I have a function foo. It takes an object of this type as its parameters
interface Foo {
  bar: number,
  baz: number,
  enabled?: boolean,
}

When enabled is not provided by the user or when it is false, foo would return an object of type Result
interface Result {
  result: number
}

so it just adds these two numbers as in

function foo({bar, baz}: Foo): Result {
  return {
    result: bar + baz
  }
}

Here is the question: When enabled is provide in the params and it is set to true, I want the function returns another type of result, where it has another field isEqual, which indicates if bar and baz is equal. so like
interface AnotherResult {
   result : number,
   isEqual: boolean
}

Here is how we can use this function
const {result} = foo({baz: 1, bar: 2})

// or

const {result, isEqual} = foo({baz: 1, bar: 2, enabled: true})

Ideally when the user include enabled: true in the params to foo, they can destructure  isEqual from the return value of foo and when they don't provide enabled or set enabled: false, they cannot destructure  isEqual from the return value of foo.
Here is my attempt but I cannot think of a way to dynamically determine the return value's type based on the params. I wonder if that is even possible with TypeScript
nterface Foo {
  bar: number,
  baz: number,
  enabled?: boolean,
}

interface Result {
  result: number
}

interface IsEqual {
  isEqual: boolean
}

type ResultWithIsEqualEnabled = Result & IsEqual

function foo({bar, baz, enabled = false}: Foo): ResultWithIsEqualEnabled {
  return {
    result: bar + baz
  }
}

Comment: i think the `IsEqual` interface should inherit `Result` interface, rather than combine then with `&` operator
Comment: or composition is better? Not sure...
Answer: You can use function overloads:
interface Foo {
  bar: number,
  baz: number,
}

interface FooEnabled extends Foo {
  enabled: true,
}

interface Result {
  result: number;
}

interface IsEqual extends Result {
  isEqual: boolean
}

function foo(foo: FooEnabled): IsEqual;
function foo<T extends Foo>(foo: T): Result;
function foo({bar, baz, enabled}: FooEnabled): Result | IsEqual {
  const result = baz + bar;

  if (enabled) {
    return {
      result,
      isEqual: bar === baz,
    }
  }

  return {
    result,
  }
}

const {result} = foo({
  bar: 5,
  baz: 5,
});

const {result: anotherOneResult, isEqual} = foo({
  bar: 5,
  baz: 5,
  enabled: true,
})

Answer: You can define multiple return types for a function in typescript. For your example you can do it like this :
    function foo({bar, baz,enabled=false}: Foo): Result | AnotherResult {
       return (enabled==true)?{result: bar + baz, isEqual: true}: {result: bar + baz} ;
    }


What is the cost of pagers?

Question: Two brothers have broken arcade machines and they sell them each for the amount of machines there are. They use the money to buy cell phones priced at \$10 each and one pager which is less than \$10. If they divide the devices (cell phones and pager) between them so that they each have the same amount of devices. How much does the pager cost?
I tried solving for P where P = cost of pager
and I also tried substituting multiple amounts of n machines and, my buddy thinks we fell into the Pigeonhole Principle.
How can I proceed to solve this?
Answer: If they have $n$ broken machines, they sell the lot for $n^2$ dollars.  We have $n^2=10a+p$ where $p$ is the price of the pager, less than $10$, and $a$ is the number of cell phones.  They have $a+1$ devices, which they are able to divide evenly, so $a$ is odd.  If you look at the list of square numbers, you can quickly find the value of $p$.  You should prove that given $n^2=10a+p$ with $p \lt 10$ and $a$ odd, $p$ must have that value.  Write $n=10c+d$, square it, and see what $d$ can lead to $a$ being odd.

What is the cost of pagers?


Are all modes relative to Ionian (major) in Roman numeral analysis?

Question: I saw in this Wikipedia article that there are a lot of flats and sharps in the modal natural chords. And I was wondering if it's because they all refer to Ionian.

So in Aeolian the "bIII" chord is read "take the 3rd chord from Ionian, and flatten its root; then use this flattened root and make a major chord from it since the roman numerals are capitalized". Does that sound right?
Borrowing chords from a parallel mode then is just a matter of picking chords from this table (I saw this video on modal interchange). So the resulting non-diatonic chord progression, for example I bVII IV bII, is still always in reference to Ionian (?). Meaning, bVII in this progression is read "take the 7th chord from Ionian, flatten its root, use it to make a major chord".
Comment: It's more accurate to use 'major' instead of 'Ionian' in your title.
Answer: Yes, you're correct! (One might say that it's actually relative to major instead of Ionian, but that's being pretty fussy.)
The only thing to watch out for is the accidentals that are "hidden" in some of the Roman numerals. Imagine you're in D and you want to add in the II chord that's borrowed from Lydian. There's no accidental with that II Roman numeral, so you might just think we have a regular supertonic chord in D. But remember that the ii chord is typically minor in major/Ionian, and this II chord is major, thus requiring a G♯. Another way to think of this is that Lydian has the raised fourth scale degree, which would again result in that G♯.
Comment: Or - hark back to D Lydian's parent - A major. Which contains that extra sharp - G#!
Comment: Also, folks should keep in mind that some symbol conventions use upper case for any chord quality - like II for the minor supertonic triad in a major key. That mostly older convention can be confusing.
Answer: Consider, with modes of the major scale, that each is related to that major. Write them in a circle - each follows that circle, starting on a different note as it goes round.
Yours is one way to look at it; I prefer referencing the parent key. So, D Dorian, E Phrygian, F Lydian etc. all use the same chords as their parent key - C major. C Dorian, D Phrygian, Eb Lydian etc. all use the same chords as B♭ major.
Of course there are going to be lots of sharps and flats! There are in any altered notes! There's also lots of naturals, as they will be altered from the original sharps and flats!
That table may work for you, but I would instead be thinking along the lines (parallels) of G Ionian - G notes. G Dorian - F notes. G Phrygian - Eb notes. G Lydian - D notes. G Mixolydian - C notes, etc.
Reference tends to return to the major scale - that's the usual datum point.


pessoal eu não sei de onde vem o erro de sintaxe da linha " else " no final ,poderiam me ajudar

Question: <?php
  require("conexaobancodedados_Model.php");
  $nomeEvento = $_POST['nome_evento'];
  $descricaoEvento = $_POST['descricao_evento'];
  $imagem = $_FILES['imagem']['tmp_name'];
  $tamanho = $_FILES['imagem']['size'];
  $tipo = $_FILES['imagem']['type'];
  $nome = $_FILES['imagem']['name'];

  if ( $imagem != "none" )
  {
      $fp = fopen($imagem, "rb");
      $conteudo = fread($fp, $tamanho);
      $conteudo = addslashes($conteudo);
      fclose($fp);

  $queryInsercao = "INSERT INTO tabela_imagens (nome_evento, descrição_evento, nome_imagem, tamanho_imagem, tipo_imagem, imagem) VALUES ('$nomeEvento', '$descricaoEvento','$nome','$tamanho', '$tipo','$conteudo')";

   mysql_query($queryInsercao) or die("Algo deu errado ao inserir o registro. Tente novamente.");
  echo 'Registro inserido com sucesso!';
  header('Location: index.php');
   if(mysql_affected_rows($conexao) > 0) {
       print "A imagem foi salva na base de dados.";
   }else{
       print "Não foi possível salvar a imagem na base de dados.";
   }
  else{
      print "Não foi possível carregar a imagem.";
    }

Comment: Qual erro? em qual linha? em qual `else`?
Comment: @hugo você deveria explicar melhor sua dúvida inserindo comentários em partes do código, veja como fazer [stack](https://pt.stackoverflow.com/help/how-to-ask)
Comment: Olá hugo, seja bem vindo ao SOpt! Como você é novato, sugiro ver [como fazer uma boa pergunta](https://pt.stackoverflow.com/help/how-to-ask) ou se ainda tiver dúvidas de como funciona o site, você pode fazer um pequeno [tour por aqui](https://pt.stackoverflow.com/tour).
Answer: Tá faltando uma } pra fechar o primeiro if
<?php
require("conexaobancodedados_Model.php");
$nomeEvento = $_POST['nome_evento'];
$descricaoEvento = $_POST['descricao_evento'];
$imagem = $_FILES['imagem']['tmp_name'];
$tamanho = $_FILES['imagem']['size'];
$tipo = $_FILES['imagem']['type'];
$nome = $_FILES['imagem']['name'];

if ( $imagem != "none" )
{
    $fp = fopen($imagem, "rb");
    $conteudo = fread($fp, $tamanho);
    $conteudo = addslashes($conteudo);
    fclose($fp);

    $queryInsercao = "INSERT INTO tabela_imagens (nome_evento, descrição_evento, nome_imagem, tamanho_imagem, tipo_imagem, imagem) VALUES ('$nomeEvento', '$descricaoEvento','$nome','$tamanho', '$tipo','$conteudo')";

    mysql_query($queryInsercao) or die("Algo deu errado ao inserir o registro. Tente novamente.");
    echo 'Registro inserido com sucesso!';
    header('Location: index.php');
    if(mysql_affected_rows($conexao) > 0) {
        print "A imagem foi salva na base de dados.";
    }else{
        print "Não foi possível salvar a imagem na base de dados.";
    }
} // Falta esta chave
else {
    print "Não foi possível carregar a imagem.";
}

Comment: Posso editar e pôr o código inteiro?
Comment: Sim, sem problemas, estou no celular.... Muito ruim de mexer com o código aqui
Comment: Tranquilo, editei. Eu sei como é ruim mexer em respostas pelo celular.
Comment: Pois é... rs. Obrigado =]


How to install specific apache version?

Question: I developed one module for apache 2.4 server, I want to test my module with different apache versions.
I installed apache2.4 using following command.
apt-get -y install apache2
Can I install previous apache versions using apt-get?
Answer: You can install the package name with version number
apt-get install <packagename>=<complete version name>

The below command will show the list of versions
apt-cache showpkg <pachagename>

How to install specific apache version?


Dealing with probable outliers in the dependent variable

Question: I am trying to fit a simple regression to a data set with ~45,000 observations. The dependent variable is revenue growth, but I'm concerned some observed values are incorrectly entered data.
To elaborate: The mean growth was about 6% (standard deviation is approximately 18%), but observations range from -100% to 200%. I'm certain 200% was incorrectly entered, but there is a decent number of observations above 100% which disconcerts me. While growth in this range is plausible and has been observed, I have doubts that all of them are accurate (my skepticism is an increasing function of the number of observations in this range).
What is the best way to deal with this data, especially because there are too many observations to check manually? Should I remove all of these data points and run the model for on data which I am confident is correct? Or will this bias the model because it bounds the dependent variable below 100%? Is there something more sophisticated that can salvage these observations?
Answer: One of the ways to deal with outliers is to use tukey border values to either set the data outside it to missing or to set it to the border value. For the lower part of the distribution it is defined as $Q1-1.5IQR$ and for the higher part $Q3 + 1.5 IQR$, where Q1 and Q3 are 1st and 3rd quartile values, and IQR is inter-quartile range. The values lower than the first, or higher than the second value should be seto to NA or replaced with these border values. I prefer setting the values to missing if there are not more than 10% of missing values after this transformation.
The other way to deal with the problem is to use $M\pm3SD$. You set all values above and below these values to NA.
Here are two functions in R you can use to do the work for you.
<code># Function identifies either tukey (tuk) or sd (sd) border values (type),
# and the magnitude of the range (level) - normal tukey range is 1.5IQR,
# and usual range with SD is 3)

GRW <- function(x, type, level){
  x <- unlist(x)
  if (type == "tuk"){
    IQR <- quantile(x,0.75, na.rm = T) - quantile(x,0.25, na.rm=T)
    Q1 <- quantile(x, 0.25, na.rm=T) - level*IQR
    Q2 <- quantile(x, 0.75, na.rm=T) + level*IQR
    names(Q1) <- NULL
    names(Q2) <- NULL
    return (c(Q1 = Q1, Q2 = Q2))
  }

  if (type == "sd"){
    SD_l <- mean(x, na.rm=T) - level*sd(x, na.rm=T)
    SD_h <- mean(x, na.rm=T) + level*sd(x, na.rm=T)
    names(SD_l) <- NULL
    names(SD_h) <- NULL
    return(c(SD_l = SD_l, SD_h = SD_h))
  }
}

# Function returns vector with tukey/sd (type) with manually defined
# range (level), only on positive(pos), negative (neg) or both ends (double)
# and it either replaces the outliers with border values (replace = TRUE)
# or sets them to NA (replace = FALSE)

REPL <- function (var, type, level, end, replace) {
  # Only positive end
  if (end == "pos") {
    if (replace == FALSE) {
      var[var>GRW(var,type,level)[2]] <- NA
      var
    }
    if (replace == TRUE){
      var[var>GRW(var,type,level)[2]] <- GRW(var,type,level)[2]
      var
    }
  }

  # Only negative end
  if (end == "neg") {
    if (replace == FALSE) {
      var[var<GRW(var,type,level)[1]] <- NA
      var
    }
    if (replace == TRUE){
      var[var<GRW(var,type,level)[1]] <- GRW(var,type,level)[1]
      var
    }
  }

  # Double end
  if (end == "double"){
    if (replace == FALSE) {
      var[var<GRW(var,type,level)[1]] <- NA
      var[var>GRW(var,type,level)[2]] <- NA
      var
    }
    if (replace == TRUE){
      var[var<GRW(var,type,level)[1]] <- GRW(var,type,level)[1]
      var[var>GRW(var,type,level)[2]] <- GRW(var,type,level)[2]
      var
    }
  }
  var
}
</code>
Btw. if you want to check for outliers visually, use the function boxplot(), or in ggplot geom_boxplot()
Comment: Tukey's suggestion was just that points more than 1.5 IQR away from the nearer quartile be plotted separately on box plots. The idea that this is a criterion for ignoring or truncating data can only come from others. It's a misuse of his name to suggest otherwise.
Comment: It's good to know that, I wasn't aware of that! Thanks for pointing that out.
Answer: Aside from the technicalities of identifying outliers (Tukey, SD, hotelling t2 for multivariate data, etc) I think that the first question should be: Why do we want to identify outliers? If your primary purpose is e.g. to model basic principles for economic growth in the general body of companies, then you may want to exclude rocket companies from your data, since they obviously work by a different mechanism.
Conversely, you may want to identify potential rockets. Then you will identify a small set of outliers from your general data swarm and in a subsequent step discard those outliers that arise from simple input errors. Then you can use some clever modeling principle or deep analysis to identify causes for these observations to stand out from the others...
Your fundamental analysis question will determine the best approach for identifying outliers, but as a general principle you should make sure to check why observations are outliers. Not just ascertain that they are.
I don't know much about quantitative economics, but why not make e.g. a normality test before/after a series of transformations (e.g. log transformations) and see if observations become modelable before deciding on . aprinciple for identifying outliers. Then, as I mentioned above, if your aim is to find sort of general principles of economic growth, you may want to sort out not only obvious errors but also those observations that are governed by other principles, since they probably will not be well described by general mechanisms.

EDIT:
Your comment suggests that you may be more interested in identifying the interesting outliers than modeling the bulk of the observations. Then why not train a classification model? You haven't specified your independent data, but I'm guessing you have some input parameters...
Then train your independent data on a 3 class problem:
1. Normal companies
2. Apparent faulty entries
3. Rockets
You may also want to add other categories, such as bombs...
That way you could investigate whether there is something systematically different between the different types of outliers. An analysis of important variables distinguishing different types of companies could then help you make an informed decision on how to treat your outliers in relation to your subsequent analyses (e.g. whether they should be included in the main model, completely discarded or analysed separately in a different model).
HTH HAND
Carl
Comment: Thanks, Carl. My main problem is not understanding why they are outliers--as you said, most are 'rocket companies' or measurement errors--but identifying whether an outlier is a measurement error or a rocket company. A more felicitous way of expressing my question is: Without knowing which type of outlier (rocket company or input error), is it better to work with all of the data (some of questionable quality) or remove all of the questionable observations entirely?


Avoiding PHP timeout when geocoding many addresses - preferred method?

Question: I have a script that's taking in a ton of address data from a CSV, converting it to JSON, and along the way it hits the Google Maps API to get the latitude and longitude of each address. It then writes the whole thing to a .json file that is used by another widget. This works well for small numbers of addresses but some of the files I'm importing have hundreds of addresses. I have considered several ways around this:

Queues: The problem with this one seems to be that I would have to save an object for each address and I don't want to completely fill up my database with address objects. I would then also have to somehow detect the completion of the queue and retrieve all those objects from the database to generate my complete json file. I worry about whether the server will deal with this well.
Some other Google Maps API: Am I even using the correct Google Maps API for this? Is there one that can get a bunch of coordinates for a bunch of addresses in one HTTP request? I couldn't find one but that doesn't mean it's not existing.
Feeds API (or some other core or contrib API for getting tons of data): It occurs to me that my hand-rolled solution might be circumventing some more Drupal-correct way to accomplish this task. Does Drupal offer something for making big batches of HTTP requests that I'm just missing?

So, basically my question is: what's the most Drupalish way to make and process a large number of HTTP requests from a module?
Answer: It seems to me that your only option is to go with a PHP CLI script implementation. You can learn more here: http://www.php-cli.com/
In PHP in general, whenever you have a long running task, it's best to go with PHP CLI as it doesn't impose a timeout limit and have larger memory limits by default. Note here that PHP CLI and the PHP used to server web pages have different settings that you can manage separately.
Once you have a PHP CLI script in place, setup a standard Linux CRON task to hit that script say every hour or every day.
In the context of Drupal, you might want to check this post: Do I need a cron task for processing a queue? and also check the Elysia CRON module https://www.drupal.org/project/elysia_cron as they might be helpful but I think in your case you're better of with a standard PHP CLI script.
Also, keep in mind that you can call Drush commands from a PHP CLI script very easily. I have a script that runs updates and CRON automatically on all Drupal instances running on web server and it's a huge advantage. You can also look into implementing your custom Drush commands.
Good luck.
Comment: Yes, I know how to use Drupal's queues and have implemented them before. The part that is stumping me is that I am reluctant to do it because it requires saving every address as an object, and I don't know how/when I would write to the output file.
Comment: I'm suggesting you use a PHP CLI script that lives outside Drupal to get the job done. You can even bootstrap Drupal from within that script if you need to save your output at the end.
Answer: I ended up solving this by using the Geocod.io API and the PHP library built for it. It supports batch requests and allows up to 2500 free addresses per day.


SCCM 2007 R2 Win 7 Deployment client restarting after WinPE boot

Question: I have tried to deploy windows 7 through SCCM, I have it all setup.
On the first deployment the PC boots into PXE gets an IP then loads the WinPE. It then shows a starting windows box. The box then disappears and after a few seconds the computer restarts.
Any Ideas?
Which logs should I be checking
I have also tried to inject the drivers for that PCs network adapter but this didnt work.
I looked At the smsts log file on the client and found this error "exiting with return Code 0x80004005 date time ... component TSPXE.
Thanks
Answer: That's a generic "Can't talk to the Management Point" error. This is usually one of a couple things:

The MP isn't assigned correctly in the TS file (which if you're using a generated PXE image, it's right, unless you have SCCM wildly misconfigured)
The MP isn't in the local subnet and WinPE can't get to it (there's a whole variety of possibilities here, but all basic network stuff)
The certificate you configured in the PXE image doesn't match, has the wrong password, or something similar.

If you've got a pretty basic network configuration going, try using Wireshark to listen in right before the reboot. You'll likely see some sort of negotiation ending in failure. That should point you in the right direction.
Comment: Can you attach logs on this site?
Comment: You can edit the question and add the logs, or you can put them on another site and hotlink to them.
Comment: The MP was not configured properly. I started from scrath and now all is well. There was also a webdav configuration issue.


Proof $\forall n\in\mathbb{N}$, that $9|10^n-1$ by mathematical induction

Question: I think I proved this but I am not to confident in my proof. I am also not that good at formating my proofs so any feedback would be appreciated :)
Let $P(n)=9|10^n-1$
Base Case:
$9|10^1-1\implies9|9\checkmark$
So we have proven the base case.
Induction Step:
$$9|10^n-1\implies9k=10^n-1\implies10^n=9k+1$$
$$9|10^{n+1}-1\implies9|(9k+1)\cdot10-1\implies9|90k+9$$
Every term in the above has a common factor of 9 hence the left divides the right. We have thus shown that $P(n)\implies P(n+1)$ with a base case. Therefore by the principle of induction $P(n)$ holds $\forall n\in\mathbb{N}$.
Edit:
The second line of the induction step was flawed as it didn't really prove anything. The fixed version goes as follows:
$$10^{n+1}=(9k+1)\cdot10\implies10^{n+1}-1=90k+10-1\implies10^{n+1}-1=90k+9$$
We can see that this $10^{n+1}-1=90k+9$ is divisible by 9. We have thus shown that $P(n)\implies P(n+1)$ with a base case. Therefore, by the principle of induction, $P(n)$ holds $\forall n\in\mathbb{N}$.
Comment: Your proof is not good because you suppose that $P(n+1)$ is true...
Comment: @BillDubuque What you wrote makes a lot of sense. But I don't think that it justifies closing this question as a duplicate of two other questions that contain other proofs of the same statement. We (as a group) could adopt a policy according to which it would be inappropriate to post question of the sort  "Please check my proof of […]" unless the author stated the specific points where they have doubts. Before that happens, I don't think that this question should be closed (unless we find another similar attempted proof).
Comment: Your implies arrows are going the wrong way in the second line to show that $P(n) \implies P(n+1)$. An easier way might be to say that $9|(10^n-1) \implies 9|((10^n-1)\cdot 10)\implies 9|((10^n-1)\cdot 10 + 9) \implies 9|(10^{n+1}-1)$.
Comment: **Dupe** of [this](https://math.stackexchange.com/questions/2375325/prove-4n-1-is-divisible-by-3-for-all-n-geq1) and [this](https://math.stackexchange.com/questions/1179019/prove-with-induction-that-11-divides-102n-1-for-all-natural-numbers) and *hundreds* of others. **Please don't reopen dupes of FAQs**
Comment: @JoséCarlosSantos I'm very disappointed to hear that, since it essentially destroys attempts at site organization (which are already difficult enough as it is w/o this complication). Others (including at least one mod - Xander) have espoused similar views to mine on SV posts. The dupes don't (only) contain "other" proofs - they contain the same (common) proof too and, furthermore, they give much elaboration that likely helps one to avoid such oversights.
Comment: You have the right idea, except you wrote the arrows in the wrong direction in the 2nd displayed inference in your induction step. What you meant was: the inductive hypothesis implies $\,10^{n+1}-1 = 9(10k+1)\,$ so $9$ divides $10^{n+1}-1,\,$ which  completes the proof of the inductive step. To make the induction step *completely obvious* I highly recommend using the the method in [this answer](https://math.stackexchange.com/a/2375354/242) in the linked dupe.
Comment: @Peter This question was originally closed as a dupe of [this question](https://math.stackexchange.com/q/2375325/446262) and of [this one](https://math.stackexchange.com/q/1179019/446262), none of which is a proof-verification question.
Comment: @Jose  A proper PV question is a  question about some *specific* point of the proof where the author has doubts, along with context explaining why those doubts exist - not an open ended "please check my *entire* proof". Often such questions can be posed in comments on an answer in a dupe  (and they help clarify the answer). If we allow open ended "check my whole proof" questions then we will  have hundreds of matches to  basic questions that will swamp search results with matches that are mostly useless (showing only answers addressing trivial oversights etc vs. the real proof).
Comment: @jose Usually the best way to handle questions like this is to close them as dupes, then leave a comment pointing out the (usually trivial) oversight (and if the oversight is common enough to be helpful to others there might be a a post to link to on that particular type of error), then eventually delete the question to stop it from cluttering search results on the *actual* proof. But in many cases once the OP reads the dupes the answer becomes immediately clear (and if not a further comment or two usually resolves it, and may help to polish rough points in answers in the dupes).
Comment: ... with the goal being that eventually the (canonical) dupe tagets will converge to "proofs from the book" after enough iterations and feedback from readers. But "the book" is not helpful if its index is so cluttered with unhelpful references that you cannot easily locate the proofs (which is precisely what is happening here for FAQs like this question).
Comment: You can prove statements of this kind much easier with modular arithmetic. In this case, the induction is not very difficult, but in more complicated situations it can quickly get cumbersome. In the given case , there is an even easier way if you think of the decimal repsentation of $10^n-1$ , only nines are occuring.
Comment: @BillDubuque No, it is not a duplicate. This question is about checking a proof, not about how to prove something.
Comment: @JoséCarlosSantos But induction proofs of this kind (to be checked) have been posted many many times, so I have to agree Bill.
Comment: @JoséCarlosSantos That would mean that questions should be reopened because they were closed for the wrong reason , even if there is a suitable reason to close them. Not my philosophy !
Comment: @amWhy What you wrote that is relevant is not true, and what that is true is not relevant.
Comment: Eight comments from Bill. Half of all comments here.  I wrote only one, and have since deleted it, because I'm sick said user's offensiveness; it was both relevant and true.
Answer: I think you're almost all the way there-- the main feedback I'd give is around your final statement:
$$9|10^{n+1}-1\implies9|(9k+1)\cdot10-1\implies9|90k+9$$
Above you're assuming what you want to prove. Try working backwards starting with what you know to get to what you want to prove. Here, try the following to get started:
$$10^n = 9k + 1 \implies 10^{n+1} = (9k + 1) \cdot 10 \implies 10^{n+1} - 1 = ... $$
N.B. Also be sure to declare what $k$ is when you use it.
I hope this helps!
Answer: When you write $9\mid10^n-1\implies9k=10^n-1$, you should say what that $k$ is. Something like "$9k=10^n-1$" for some non-negative integer $k$.
And then your aim is to prove that $9\mid10^{n+1}-1$. That's not what you do. You start from $9\mid10^{n+1}-1$ and then you see what you can conclude from that.


Maximal value of $\vert r^2-n\vert$ with a special condition

Question: let $M,n\in \mathbb{N}$ and $R=\lbrace r\in \mathbb{N} \mid \vert r- \sqrt{n}\vert <M<2\sqrt{n}\rbrace $. I have to show that the maximal value of $\vert r^2-n\vert $ for $r\in R$ is at most $(M-1)^2+2M\lceil \sqrt{n}\rceil$.
I found out that we can write each $r\in R$ as $r= \lceil \sqrt{n}\rceil + i$ with $i=-M, \dots ,M-1$. If we look at $\vert r^2-n \vert$ and consider the two cases $r^2-n\geq 0$ and $r^2-n<0$ then the first case is quite easy, but I have problems with the second case.
Then I have $r^2-n<0$ (that means $r= \lceil \sqrt{n}\rceil + i$ for $i=-M,\dots ,-1$) but if I plugin all the stuff I get $-r^2+n=n- \lceil \sqrt{n}\rceil^2 - 2i\lceil \sqrt{n}\rceil -i^2 \leq n-\lceil \sqrt{n}\rceil^2 + 2M \lceil \sqrt{n}\rceil -M^2$, but now??
Answer: Hint: You can't plug directly $i=-M$ in the last inequality, since you do not know for which $i$ the expression is maximum (note the $-M^2$...). However you have
$$n-\lceil \sqrt{n} \rceil^2 -2i \lceil \sqrt{n} \rceil - i^2
\leq n-\lceil \sqrt{n} \rceil^2+ 2M\lceil \sqrt{n} \rceil -1. $$
Now note that $\lceil \sqrt{n} \rceil \geq \sqrt{n}$, hence $n-
\lceil \sqrt{n} \rceil^2-1 \leq 0 \leq \cdots$