Is there reserved OID space for internal enterprise CAs?

Question: When provisioning a PKI for internal use, is there a private OID space that can be used without having to pay and/or register your own OID range? Think RFC1918 addresses for OID ranges.
Answer: You can register a private enterprise and then an OID will be allocated for your use as you see fit. There is no fee.
It will be under iso.org.dod.internet.private.enterprise (22.214.171.124.4.1).
For example, my company can use: 188.8.131.52.4.1.17992 for any internal and published applications that we develop.
As voretaq7 points out, you need to internally organize and keep track of how you structure your information under your assigned node. But that's your problem. :)

Note that while the registration page says:

typically used in Simple Network Management Protocol Management Information Base configurations

that's only because SNMP is the most common usage. They are for general use.
Comment: The structure of the OID tree under your enterprise is of course, your own problem. For example `188.8.131.52.4.1.###.1` might be custom SNMP monitoring OIDs, `220.127.116.11.4.1.###.2` might be custom LDAP attributes, `22.214.171.124.4.1.###.3` might be certificate policies, etc... -- Build something sensible, or at least have a top-level hierarchy of broad categories.
Comment: @MDMarra As far as I'm aware IANA (and the ASN.1 standard) imposes no formal restriction on how you use the OID space under your enterprise number. Custom SNMP MIBs are just the most common reason organizations request an OID (e.g. Cisco has a massive sprawling tree) and the place people are most accustomed to seeing OIDs turn up. The important thing is that you use *your* OID space & don't just grab a number otherwise you may find that your company's custom "Swap Space Used" OID is Cisco's "PSU 2 supply status"
Answer: I'm not an expert, but it seems OID 1.3.9900 to 1.3.9999 may be considered such "internal use" OIDs:
As per http://oid-info.com/get/1.3 :

Interchanging partners may want, by prior agreement, to interchange
  organization identifiers allocated by an identification scheme to
  which an ICD value has been assigned, or for which the assignment of
  an ICD value is pending. The range of ICD values between 9900 and 9999
  is reserved for that effect. The interchange partners shall agree on
  the identification of the identification scheme, using one of the
  above reserved values.

A public interoperability report from the UCA International Users Group ("a not-for-profit corporation focused on assisting users and vendors in the deployment of standards [...]") seems to confirm it (page 7-15, issue 39):

[...] In the case of the 1.1.999.x.y, it is clear that this was an attempt to specify a private OID. The appropriate values for this are 1.3.9999.xx.yy .
Answer: The question is old, but still there are a couple of solutions that are not mentionned.

2.25.x selfgenerated legal OID
Quoting oid info 2.25

This enables users to generate OIDs without registering them with a registration authority.

you can easily generate your own oid under 2.25, for example with this python oneliner :
python -c 'import uuid; print(uuid.uuid4().int)'

1.1.x hijack an abandonned OID arc.
from oid info 1.1,

John Larmouth, Rapporteur for the ASN.1 standard, wrote on Jan. 27,
2003: "The addendum has never been produced. The intention was to establish such a registration authority, but it never happened, largely because there were enough Registration Authorities under other arcs."

Be careful, though. This arc has been abandonned and nothing will ever be added to it, but there are a few registered OID. I don't know if these OID were ever effectively used, but just in case, pick an unused one.

220.127.116.11.3.x Use an experimental OID, not meant to be published.
No published standard will ever use this arc, so there is no risk of OID collision. Quoting RFC 4520 section 3.1.

To avoid interoperability problems between early implementations of a "work in progress" and implementations of the published specification (e.g., the RFC), experimental OIDs SHOULD be used in "works in progress" and early implementations. OIDs under the Internet Experimental OID arc (18.104.22.168.3.x) may be used for this purpose. Practices for IANA assignment of these Internet Experimental numbers are detailed in RFC 2578 [RFC2578].

x, x > 2 a trick I like.
If you take a look at the OID tree, you'll notice that only 3 numbers are used at the root.

0 itu-t
1 iso
2 joint-iso-itu-t alias joint-iso-ccitt

And then what ? Nothing... So use 3, 4, 42, 17890714, whatever you like. Noone ever used them, and never will. Everything happens inside the 0, 1, and 2 arcs.
Edit September 2022:
Some implementation seem to impose limitations on the first 2 numbers. Openldap that I used for testing does not have any limitations and you can use whatever value you like. As @SamGinrich states in his comment, there are Microsoft product that restrict the value you may use. This is corroborated by the links he gives about-object-identifier. Admins are limited to use 4, 5 or 6. (and the second number is limited to 39). Even in this case, there is still enough room for private OID. Simply use 4.1.

There are also the solutions mentionned by others

1.3.9900 - 1.3.9999
as indicated by Cédric Dufour this is a private range. It's originally meant for data interchange but it still is a reserved range, so it should be ok too.

a registered OID. although you don't want registration, this is still to consider as it's free and easy.
See MikeyB's answer. You can register an oid. It's free.
Comment: think, the OID main branch index is limited to 6 (<= 256 / 40) according to OID coding scheme, accordingly the second one to 39, susequent ones are not limited.
Comment: Have no reference to the ASN.1 standard at hand,
https://docs.microsoft.com/en-us/windows/win32/seccertenroll/about-object-identifier
this seems authentic, summed up in the gray table.
Comment: @SamGinrich, could you add a link to the OID coding scheme you are refering to ?


Chrome html5 form validation in a jQuery pop-up dialog

Question: This is very similar to this old, unanswered question.
I have a jQuery dialog box that has a form embedded in it. The rest of the forms on my site make use of html5 browser capabilities, so I want the error messages for required form elements to be the same in the pop-up form. Short of writing my own validation to mimic the formatting of browser validation pop-ups, can anyone think of a way to get Chrome to do the validation of inside the jQuery dialog box?
Here's the code. The html5 required attribute is appearing on the element and it's being marked as user-error, it's just not being recognized by Chrome.
var form = dialog.find('form');
if (!$('#formElement')[0].checkValidity()) {
    if (element.prop('type') != 'submit') {
        form.find(':submit').first().trigger('click');
    }
    return;
}
$('#action').trigger('click');

Thanks for any help you can give!
Answer: Here is one tips & trick.

HTML5 validation is not good in all cases and can fail.
With complex websites with many popups, dynamc forms etc. you can't use only HTML5 validation because you don't have control.
Crome, Mozilla, Safari, Opera, Explorer (Edge), mobile browsers (CM, UC, Dolphin, Rocket, Yandex, Puffin, Brave, Crome...) work different and some times you need to do same things for each browsers on some other way because of it's rules and supports. Many of these browsers are on WebKit but not work same.
For your project is better to use some jQuery library for validation or simple write by own.

From my side, made dialog, fill with form, validate that form with jQuery and on particular events switch content, close dialog, open new dialog or wathever you want. Is faster and better.
Comment: Thanks so much, Ivijan! I thought this might be the case, just wanted to see if there was some work-around. Much appreciated!


Should a hook_form_alter be firing both on render and when an additional submit handler is fired?

Question: I am trying to add an additional submit handler to the user login form, to simply redirect users to the page they were on before landing on the login page (/user/login).
I have the following code attempting to store the current path/destination in the $form_state storage which is working as I expected when the original form_alter is run on render as it alters the redirect property of form_state to the previous page.
However, when the form is submitted, the form_alter is fired again, but this time the form_state storage is empty, thus the current_path/destination is now set to /user/login which is not where the user should be redirected to.
Here is the code I have at the moment, any help would be appreciated as to why the form_alter is run again on form submit:
function MODULE_form_user_login_form_alter(&$form, FormStateInterface $form_state, $form_id) {
  $form['#submit'][] = '_module_custom_user_login_form_submit';
  if (is_null($form_state->get('redirect_dest'))) {
    $destination = $_SERVER['HTTP_REFERER'];
    $form_state->set('redirect_dest', $destination);
  }
}

function _module_custom_user_login_form_submit($form, FormStateInterface &$form_state) {
  $destination = $form_state->get('redirect_dest');
  $form_state->setRedirect($destination);
}

Answer: I think the chain of events is different. The form gets cached with no or the wrong redirect_dest set. Then the form is submitted and redirected to the form itself. This is now a new form build, because you didn't request a rebuild. Only in a rebuild you keep the form_state.
Solution:
Drupal has the feature to redirect built in. Add the destination on the page linking to the user login:
Url::fromRoute('user.login', [], ['query' => $destination])

Edit (new module):
To add the destination automatically you can use this module:
https://www.drupal.org/sandbox/gnuget/2824414
This is a js solution, so it doesn't interfere with caching. I think in this case you can use a sandbox module, because the site won't break if the js code stops working.
Comment: Thanks for helping, I have already tried the module recommended, but the PHP snippets feature has been removed in the Drupal 8 port.

I don't think that it has anything to do with a rebuild, as it is simply the user login form, not a multi-step form.  My understanding was that hook_form_alter is only fired when the form is rendered, why is it when I have a breakpoint inside form_alter it is hit again before the breakpoint in the submit function when submitted?  I would understand hitting it again if I were redirected back to the same page, but surely the submit handler must be hit first?
Comment: Most times the form build/alter is not fired, when a form is rendered, because of caching. But it is on POST requests, because these are not cached.
Comment: I found a module that adds the destination in javascript, so there shouldn't be any problems with caching, see edit.
Comment: Thanks for the module link, it's helping a lot more than the other ones I've already tried.


Area using $\iint dxdy$

Question: I know about finding a volume under a curve using $\iint f(x,y) dxdy$.
But what $\iint dxdy$ describe? Should I consider $f = 1$? I thought if I need to find an area, not the volume shouldn't the $\text{Area} = \iint 0 dx dy$. So that the $z$-axis is always zero? But of course, the area will also be zero.
I'm super confused about this concept. Why should I care to find an Area under region? Isn't that volume is something we should consider and not just the area?
Answer: Yes, consider $f(x,y)=1$. The volume under this curve is $1$ (the height) times the area of the base, so the numerical value of volume coincides with the area: they're the same thing.
Comment: Sorry. I am little confused back then. Now I understood. Thanks for explaining.
Comment: But shouldn't f(x,y) = 0. so that z-axis (height) is always zero and not one? So that it have no 3rd dimension and we can just multiply the length and breadth (dx and dy) in x and y axis to compute the area?
Comment: We are not multiplying length and breadth because we're not finding the area of a rectangle, but an arbitrary region. We're multiplying the area of the base and the height on top of the base. If $f=0$ then the volume is $0$.
Comment: @VigneshWar glad to help!
Answer: If $B$ is a measurable and bounded subset of $ \mathbb R^2$, then the area of $B$ is given by
$\iint_B 1 d(x,y).$
Answer: One of the most common ways to think of a double integral is to think of it as the volume under a surface created by a function of two variables $z=f(x,y)$ and bounded by a region $R$ (typically rectangular in shape) in the $xy$ plane. If the given function of two variables is $f(x,y)=1$, then what you're basically doing is you're finding the volume of a solid whose height is $1$ and the base area is the area of the given region $R$. The volume of a solid whose height is $1$ is numerically equal to its base area. That's why
$$\iint_{R}1\,dx\,dy=area\ of\ region\ R.$$
Answer: You can think of $\int \int f(x,y)dxdy$ as "weighted sum" of the region. Your $f(x,y)$ function tells you "how important" each point is. If your weight is $1$, then each point is worth one unit, so the integral just "adds up" the points, and you get the area. If $f(x,y)$ is the height, then the integral is adding up all those heights, so you get the volume.
In calculus, there is a distinction between things that are infinitesimally small, versus things that are zero. The height is not zero, it is an infinitesimal. So instead of taking  $\int \int 0dxdy$, we should take $\int \int dxdydz$. This is then the volume of the region. We can factor out the $dz$ and consider this to be $(\int \int dxdy)dz$.  The quantity within the parentheses is the area; if we were calculating the volume of a region, we could calculate it by integrating along the $z$-axis and finding the area of each cross section, i.e. $dV =Adz$.
Keep in mind that whenever you calculated the size of a geometric quantity, anything of a larger dimension will be "infinitely"  large, while anything of a smaller dimension will be "infinitesimally" small. For instance, if you're calculating areas, then any volume will have an infinite area (it's the sum of infinitely many areas stacked on top of each other), and any line segment will have infinitesimal area. We need to distinguish between a line segment having no area, versus a line segment having no measure at all. When we measure a line segment with cm$^2$, we will get zero, but when we measure it with cm, we get a positive number. And if we want to find the area of a region by integrating a bunch of lengths, then we need to distinguish between these two measures; when we integrate a bunch of lengths, we're adding up a bunch of lengths that each have zero area individually, but together have positive area.
Similarly, by multiplying $dxdy$ by the height, and treating the height as being zero to get the area, you're measuring the region in three dimensions. And measuring area (a two-dimensional quantity) in three dimensional units results in zero.

Area using $\iint dxdy$


Tabela editável com Jquery e PHP problem

Question: Boa tarde,
Estou com um problema, a uns dias tentando e não consigo resolver,
estou tentando fazer um tabela editável, o problema é que depois que eu pópulo a tabela com json não consigo fazer nada com as , tudo que eu coloco via "append" não é reconhecido depois.
$("button[name='visualizar']").on('click', function() {
    var i = 0;
    $("#tabela").empty();
    $.ajax({
        type: "post",
        dataType: "json",
        url: "php/select_db.php",
        success: function(dados) {
            for (i = 0; dados.length > i; i++) {
                $("#tabela").append("
" + dados[i].modulo + "	" + dados[i].codigo + "
");
            }
        },
        error: function() {
            alert("fail");
        }
        //$("#aviso2").toggle('slow');
    });
});

até aqui tudo beleza//
o código acima insere os dados na tabela, mas essas células que são inseridas via jquery não são reconhecidas posteriormente.
se eu usar $("#tabela tbody tr td").dblclick(function()}; nada acontece.
agora se eu criar uma tabela teste diretamente no front a função reconhece a tabela e executa o código que estiver dentro da função.
se alguém puder me ajudar, já pesquisei bastante e não encontrei o que causa este problema.
Muito obrigado.
Comment: no inicio do documento javascript você está usando o `$(document).ready(function(){})`?
Answer: Olá, acredito que seu problema esteja no escopo da árvore de DOM.
Quando você carrega um site, é gerado uma árvore de DOM e a inserção de fragmentos HTML posteriores não estarão nessa árvore e assim não serão reconhecidos.
Tenta isso depois:
 $('body').on('click','td',function(){
              //sua função
           });

A documentação: http://api.jquery.com/on/ ; pelo que entendo, o on() está acima da leitura do clique padrão e funciona desde que o elemento exista
Comment: perfeito, muito obrigado amigo. funcionou :D


search element in stl containers

Question: So I was looking for a way to search a string in a list of strings. I have coded the following
bool contains(const std::list<std::string>& data, const std::string& str)
{
        std::list<std::string>::iterator i;
        for(i=data.begin(); i!=data.end(); ++i)
        {
                if (str == *i)
                        return true;
        }

        return false;

}

This is just a very basic code. I m aware of the find  method but it takes in the start and end . Ideal solution would be taking entire container. There are some boost methods for the same , however I m not sure how to use them. can you give some example for boost find for generic searching of element.
Comment: A small recommendation, as of now when calling your function the parameters are _copied_, which can be bad if your list is long. Use (const) references instead: `bool contains(const std::list &data, const std::string &str)`
Answer: std::find can takes in the start and end iterators, which basically determine the whole container:
std::find(data.begin(), data.end(), str);

Answer: Use Boost.Range:
#include <boost/range/algorithm/find.hpp>

auto i = boost::find(container, value);
if (i != boost::end(container))
  doSomething(*i);

Comment: No, you must ensure that i != boost::end(container), before you dereference i.
Comment: i = boost::find(data, value);
        if(*i == value)
                cout<< "value present";
        else
                cout<< "value not present";
useful for checking value
Comment: auto i = boost::find(adresses, adress);
if(i != boost::end(adresses) && (*i)!= adress){ .... }

On compiling I get these errros : CoverDownloader.h:135:39: error: no match for 'operator*' in '*i'
Any ideas why the are coming ?
Comment: First of all, the condition is meaningless, because find() can return either an iterator to "adress" or end iterator. Ensure that your compiler supports C++0x "auto", otherwise define the iterator type explicitly.
Answer: Why not using something along the lines of this :
template <typename container, typename T>
bool contains(container& container, T& elt)
{
   return (std::find(container.begin(), container.end, elt) != container.end();
}

Comment: I think this is basically a correct answer, so +1. But looking at the end of the question, it may be that the real question here is "how do I call `boost::find`?"
Comment: You got the argument order wrong, should be `std::find(container.begin(), container.end, elt)`
Comment: `container` should be passed by constant reference (and `elt` too, if efficiency is a concern).

search element in stl containers


Greenplum demo cluster regression test installcheck-good is not working

Question: Greenplum demo cluster regression test installcheck-good is not working
I have built  the code for greenplum open source project as per steps given at https://github.com/greenplum-db/gpdb. I could build the code. However there is a section "Basic GPDB source configuration, compilation, gpdemo cluster creation and test execution example". While running installcheck-good which is supposed to run a few regression test to make sure that cluster is installed properly.
However facing issue with some select statements failing. I am not clear at what steps those database tables are expected to create. So not sure how to fix this issue. Any help on this appreciated. Below is log from run :
[priti@priti-vm gpdb-master]$ make installcheck-good
make -C src/test installcheck-good
make[1]: Entering directory /home/priti/gpdb-master/src/test'
make -C regress installcheck-good
make[2]: Entering directory/home/priti/gpdb-master/src/test/regress'
make -C ../../../src/port all
make[3]: Entering directory /home/priti/gpdb-master/src/port'
make[3]: Nothing to be done forall'.
make[3]: Leaving directory /home/priti/gpdb-master/src/port'
make -C ../../../contrib/spi refint.so autoinc.so
make[3]: Entering directory/home/priti/gpdb-master/contrib/spi'
make[3]: refint.so' is up to date.
make[3]:autoinc.so' is up to date.
make[3]: Leaving directory /home/priti/gpdb-master/contrib/spi'
rm -rf ./testtablespace
mkdir ./testtablespace
./checkinc.py
Greenplum INCLUDEDIR:    /root/greenplum/gpdb-master/include
Greenplum PKGINCLUDEDIR: /root/greenplum/gpdb-master/include/postgresql
Checking includes...
Include files are ok
if [ -z "" ]; then \
        ./pg_regress --inputdir=. --multibyte=   --init-file=./init_file  --psqldir=/home/priti/gpdb-master/bin --schedule=./parallel_schedule --schedule=./greenplum_schedule --srcdir=/home/priti/gpdb-master/src/test/regress; \
        else \
        bash kerberos/setup_test.sh; \
        PGUSER="gpadmin/kerberos-test" ./pg_regress --inputdir=. --multibyte=   --init-file=./init_file  --psqldir=/home/priti/gpdb-master/bin --schedule=./parallel_schedule --schedule=./greenplum_schedule --srcdir=/home/priti/gpdb-master/src/test/regress --host=hostname`; \
        fi
(using postmaster on Unix socket, port 15432)
ERROR:  relation "gp_segment_configuration" does not exist
LINE 1: select content, role, status, hostname from gp_segment_confi...
                                                    ^
ERROR:  relation "gp_segment_configuration" does not exist
LINE 1: ... gscp.mode, gscp.status, gscp.preferred_role from gp_segment...
                                                             ^
ERROR:  relation "gp_segment_configuration" does not exist
LINE 1: ... gscp.mode, gscp.status, gscp.preferred_role from gp_segment...
                                                             ^
ERROR:  relation "gp_segment_configuration" does not exist
LINE 1: ... gscp.mode, gscp.status, gscp.preferred_role from gp_segment...
Answer: I could resolve this error though I don't know what is exact reason.
However first time, I had faced lot of issues to do all steps in one shot ( lot of prerequisite were not clear ) and therefore I might have resulted at the end in this error.
So I took a clean machine and tried all steps as below. Also make sure that below prerequisite packages are added before starting first steps.
Prerequisites
1. create a new user as gpadmin. set password for that user
2. Make sure that password less ssh is working from root user as well as from same user to localhost.
3. Do all steps as part of new user only.
4. install below packages first
yum install -y  zlib*
yum install -y  libcurl-devel.x86_64 0:7.19.7-37.el6_5.3
yum install -y  bzip2-devel*
yum install -y bison*
yum install -y  flex*
yum install -y gcc
yum install python-crypto python-paramiko
after all this start with below steps and then regression test will also work.
su - gpadmin
Cd /home/gpadmin/gpdb-master
./configure --prefix=/home/gpadmin/gpdb-master
Make
make install
source /root/greenplum/gpdb-master/greenplum_path.sh
cd gpAux/gpdemo
make cluster
source gpdemo-env.sh
make installcheck-good
Thanks
Priti


How to prove that 2 points $\varepsilon$ and 2$\varepsilon$ are indistinguishable not only in sole case? (Smooth infinitesimal analysis)

Question: There are 2 points on the Real line: $A$ and $2A$. They are indistinguishable in sole case - if $A$ is $0$.
But how to prove that $\varepsilon$ and 2$\varepsilon$ are indistinguishable not only in sole case? ($\varepsilon$ is infinitesimal)
Thanks.
Answer: As you can find in e.g. Section 3 of O'Connor's SDG notes, the real line object $R$ of Smooth Infinitesimal Analysis satisfies the following: $$\forall x \in R.~x \neq 0 \rightarrow \exists y \in R. xy = 1$$
This means that if you can prove that some number $x$ is not equal to $0$, then you can find its multiplicative inverse $x^{-1}$ such that $x x^{-1} = 1$.
It follows that if $\varepsilon$ is a nilsquare infinitesimal, so that $\varepsilon^2 = 0$, then you cannot ever hope to prove that $\varepsilon \neq 0$. Why?
Assume you could somehow prove that $\varepsilon \neq 0$. Then, by the result above, you could find its multiplicative inverse $\varepsilon^{-1}$ satisfying $\varepsilon \varepsilon^{-1} = 1$. And once you found the multiplicative inverse, you could

Start from the equation $\varepsilon \varepsilon = 0$;
multiply both sides by $\varepsilon^{-1}$ to get $\varepsilon\varepsilon\varepsilon^{-1} = 0 \varepsilon^{-1}$;
simplify using $\varepsilon\varepsilon^{-1} = 1$ to $\varepsilon = 0 \varepsilon^{-1}$;
use the fact that $0x = 0$ holds for any $x$ to conclude that $\varepsilon = 0$.

So we'd now have that $\varepsilon \neq 0$ and $\varepsilon = 0$, a contradiction.
This means that you cannot distinguish any infinitesimal from zero: to distinguish an infinitesimal $\varepsilon$ from zero, you'd have to assume or prove that it's not zero, i.e. that $\varepsilon \neq 0$. But as we see above, $\varepsilon \neq 0$ would give rise to a contradiction!
In practice, this means that whenever you give a proof, construction or definition starting with "take an infinitesimal $\varepsilon^2 = 0$", your proof/construction/definition has to work even in the case that $\varepsilon = 0$. You can't ever rule this case out in any way.
Now, assume that you could somehow distinguish between $\varepsilon$ and $2\varepsilon$, i.e. you could somehow prove that $2\varepsilon \neq \varepsilon$. Then, since $x \neq y$ implies $x - c \neq y - c$, we'd have that $2\varepsilon - \varepsilon \neq \varepsilon - \varepsilon$, i.e. $\varepsilon \neq 0$. But that cannot be shown, as we've seen above.
Not only can you not distinguish infinitesimals from zero, but you cannot distinguish infinitesimals from each other at all. So whenever you give a proof, construction or definition starting with "take an infinitesimal $\varepsilon^2=0$", your proof/construction/definition has to work exactly the same way for every infinitesimal. You won't be able to make distinctions like "if I picked infinitesimal $a$, do something; if I picked infinitesimal $b$, do something else".

aside: The key thing that makes this work is the use of intuitionistic logic. If we were using classical logic, by the law of excluded middle we'd have that "$\varepsilon = 0$ or $\varepsilon \neq 0$": the second case yields a contradiction, so we'd conclude that the first case, $\varepsilon = 0$ holds, and therefore we'd conclude that the only nilsquare number in a field is zero. That's why Smooth Infinitesimal Analysis cannot work using classical logic. Thanks to intuitionistic logic, we don't have the law of excluded middle, so it need not be the case that "$\varepsilon = 0$ or $\varepsilon \neq 0$" holds, and Smooth Infinitesimal Analysis keeps working.
As a side remark, I'd like to point out that Smooth Infinitesimal Analysis is a particularly difficult setting for mastering intuitionistic logic.
When one learns constructive mathematics that relies on intuitionistic logic, one finds that certain argument forms and constructions one is used to no longer work. This naturally takes some getting used to. However, there's at least no new stuff to keep track of: at least initially, you're still learning largely the same mathematics, you just have to work a bit harder to prove your theorems.
This happens in Smooth Infinitesimal Analysis too. But you also get something more. Smooth Infinitesimal Analysis has anti-classical axioms, forms of reasoning that wouldn't work at all in classical logic (they'd yield contradictions), but happen to work in intuitionistic logic. So when you learn intuitionistic logic and SIA at the same time, you're forced to grapple with the fact that your old familiar tools no longer work, and you also have to master new tools that look like they shouldn't work. Most people find managing these interactions fairly tough.
Comment: Yeah, we do have $\varepsilon=0$ precisely if $\varepsilon=2\varepsilon$. So if we could show that $\varepsilon\neq 2\varepsilon$, we'd have managed to distinguish between $\varepsilon$ and zero.
Comment: @Mike_bb: The dual numbers superficially resemble the real line of Smooth Infinitesimal Analysis, but ultimately the two structures don't have much in common. In SIA you are allowed to divide by any number $x$ that is non-zero ($x \neq 0$) - the real line of SIA forms a field. In the dual numbers, this is not the case: there is a dual number $d \neq 0$ so that you cannot divide by $d$.
Comment: @Mike_bb: The proof above doesn't work for dual numbers, and is not needed for them. The dual numbers are just 2x2 matrices that have the form [[a,b],[0,a]] where $a,b\in \mathbb{R}$ - the usual set of real numbers from classical calculus, not the real line of SDG! The zero dual number is just the zero matrix [[0,0],[0,0]]. The nilsquare dual number $\varepsilon$ is the matrix [[0,1],[0,0]], which is not equal to the zero matrix simply because their entries are not the same, in particular $0\neq 1$. It does not have an inverse because its determinant is $0\cdot 0+1\cdot 0 = 0$.
Comment: @Mike_bb: No, you don't get the required contradiction if you start with $\varepsilon \neq 7$. To get the contradiction, you need the multiplicative inverse, and to construct the multiplicative inverse you use the implication $x \neq 0 \to \exists y \in R. xy = 1$ (which holds, as noted above). The analogous implication $x \neq 7 \to \exists y \in R. xy = 1$ is _not_ true, so there is no way to use the assumption $\varepsilon \neq 7$ instead of $\varepsilon \neq 0$.
Comment: Oops, it does look like a bunch of $~^{-1}$s were missing, which resulted in a wrong argument. I'm not sure when I introduced that problem. I edited it just now, so it should be fixed, please check that it makes sense to you as written now.
Comment: @Mike_bb: Alas, I don't quite understand your question/argument as written. It's probably better to ask it separately, where you can write a proper exposition of your thoughts unburdened by character limits, and other people will be able to chime in with answers and clarifying questions.
Comment: @ Z. A. K. "Now, assume that you could somehow distinguish between $ε$ and 2$ε$, i.e. you could somehow prove that 2$ε$$≠$$ε$..." if $ε$ $≠$ $0$ then 2$ε$ = $ε$ if $ε$ = $0$ and 2$ε$ is indistinguishable from $ε$ if $ε$ is indistinguishable from $0$. Is it right?
Comment: Hello. I read about dual numbers. They have $\varepsilon^2=0$ with $\varepsilon \neq 0$. I used your assumption $\varepsilon \neq 0$ in your proof above and inequality $\varepsilon \neq 0$ was false but as I mentioned in dual numbers $\varepsilon \neq 0$. How is it possible? Thanks. @Z. A. K.
Comment: How to prove for dual numbers that $\varepsilon \neq 0$ using your proof above? Thanks. Z. A. K.
Comment: Hello. Is following proof (indeed it's your proof above with more details) correct?

Let $\varepsilon^2=0$ and so we have two cases: $\varepsilon=0$ and $\varepsilon \neq 0$. For the second case we have only infinitesimal $\varepsilon$ that indinistinguishable from zero, and for this case $0$ isn't solution because we have condition $\varepsilon \neq 0$ that must holds. Is it true? @Z. A. K.
Comment: @Mike_bb: Sorry to disappoint, but I won't be able to help with your question this time. The question was already asked on the site, and was closed, meaning the community thinks it should not be answered. I certainly don't want to get on the bad side of the mods by essentially circumventing this judgment. But there's another serious reason too: a month ago I said we're near the point where asking/answering these questions becomes a bad use of time. Now we're past it. I outlined my reasons [here](https://math.stackexchange.com/a/4800117/645935) in the bad news part; my recommendation stands :(
Comment: Hello. Why do you start your proof with assumption $\varepsilon \neq 0$? If we use intuitionistic logic and pick e.g. $\varepsilon \neq 7$ then we'll obtain that $\varepsilon$ is indistinguishable from $7$. Where is my mistake at this point? Thx. @Z. A. K.
Comment: Hi. Isn't there mistake in your proof on the second line (multiply both sides by $\varepsilon$ to get $\varepsilon\varepsilon\varepsilon^{-1} = 0 \varepsilon$)? How did you get $\varepsilon^{-1}$ ? Thx. @Z. A. K.
Comment: All right now! @Z. A. K.
Comment: Hello. I want ask you about case with $\varepsilon \neq 7$ again. If I start proof with $\varepsilon \neq 7$ then I can say that there is only $\varepsilon=0$ that satisfies $\varepsilon^2=0$ but there is no non-zero infinitesimal $\varepsilon$. At this point I can say that $\varepsilon \neq 7$ is false because there is no non-zero infinitesimal $\varepsilon$ in this case and non-zero infinitesimal is indistinguishable from $7$.Where did I go wrong in my reasoning? Thanks. @Z. A. K
Comment: Is it true that:
1. If $\varepsilon \neq 7$ then we get $\varepsilon=0$
2. If we want to get non-zero infinitesimal then we use $\varepsilon \neq 0$ and get it.
?


Compactness theorem equivalences

Question: i have this equivalence to compactness theorem that i have problems to prove:
For every first-order theory $T$, every tuple $x̄$ of distinct variables and all sets $\Phi(x̄),\Psi(x̄)$ of first-order formulas, if $T\vDash\forall\bar{x}(\bigwedge\Phi(x̄)\leftrightarrow\bigvee\Psi(x̄))$ then there are finite sets $\Phi_{0}(x̄)\subseteq\Phi(x̄)$ and $,\Psi_{0}(x̄)\subseteq\Psi(x̄)$ such that $T\vDash\forall\bar{x}(\bigwedge\Phi_{0}(x̄)\leftrightarrow\bigvee\Psi_{0}(x̄))$
Comment: What have you tried?
Comment: I don't know where to start
Comment: What is the exact formulation of the compactness that you are using?
Comment: I tried with both:

- Let $T$ be a first-order theory. If every finite subset of $T$ has a model then $T$ has a model
- If $T$ is a first-order theory, $\psi$ a first-order sentence and $T \vDash\psi$, then $U\vDash\psi$ for some finite subset $U$ of $T$.
Answer: Write $\neg\Psi$ for the set containing the negation of formulas in $\Psi$. Consider only one implication for the moment. From
(0) $T\vDash\forall x(\bigwedge\Phi(x)\rightarrow\bigvee\Psi(x))$
we obtain
$T \cup \Phi(x) \cup  \neg\Psi(x)\models\bot$
By compactness, for some finite set
$T \cup \Phi_0(x) \cup  \neg\Psi(x)\models\bot$
Therefore
(1) $T \models \forall x [\bigwedge \Phi_0(x) \rightarrow  \bigvee\Psi(x)]$
The converse of (0) is equivalent to $T\vDash\forall x(\bigwedge\neg\Psi(x)\rightarrow\bigvee\neg\Phi(x))$. Therefore the same argument yield
$T \models \forall x [\bigwedge\neg\Psi_0(x) \rightarrow  \bigvee\neg\Phi(x)]$ which is equivalent to
(2) $T \models \forall x [\bigwedge\Phi(x) \rightarrow  \bigvee\Psi_0(x)]$
If you put (0), the converse of (0), (1) and (2) together you obtain
$T \models \forall x [\bigwedge\Phi(x)\rightarrow \bigwedge\Phi_0(x) \rightarrow  \bigvee\Psi(x) \rightarrow\bigwedge\Phi(x) \rightarrow  \bigvee\Psi_0(x)\rightarrow  \bigvee\Psi(x)\rightarrow \bigwedge\Phi(x) ]$
EDIT. Note that we obtain a stronger claim than required. Namely, $\bigwedge\Phi(x)\leftrightarrow \bigwedge\Phi_0(x)$ and $\bigvee\Psi(x)\leftrightarrow \bigvee\Psi_0(x)$.
Comment: I think this can be simplified. You can get finite $\Psi_0 \subseteq \Psi$ s.t. $T \cup \Phi_0 \cup \neg \Psi_0 \models \bot$ right away. Then $T \models \bigwedge \Phi_0 \to \bigvee \Psi_0$ does indeed follow as before. After that no more use of compactness is necessary because $T \models \bigvee \Psi_0 \to \bigvee \Psi$ always holds, so now you can tie everything together. (I omitted variables from my notation everywhere, they should of course be added if you want to be precise)
Comment: @MarkKamsma You are right.

Compactness theorem equivalences


ckeditor in rails with mongodb

Question: I am using ck editor in rails having database mongo db. I followed the link https://github.com/galetahub/ckeditor  . I am succes in doing work with the help of ckeditor.
since my view.html.erb code is like this
<%= f.cktext_area :description, :toolbar => 'Easy', :width => 800, :height => 200 %>

and my show page is
<%= firstname.lastname@example.com %>

it does not works for file cases.
I have my model attachment_file.rb is
class Ckeditor::AttachmentFile < Ckeditor::Asset
  has_mongoid_attached_file :data,
                            :url => "/ckeditor_assets/attachments/:id/:filename",
                            :path => ":rails_root/public/ckeditor_assets/attachments/:id/:filename"

  validates_attachment_size :data, :less_than => 100.megabytes
  validates_attachment_presence :data

  def url_thumb
    @url_thumb ||= Ckeditor::Utils.filethumb(filename)
  end
end

It is working for image cases but not working for zip file or any attachement. when it comes to the file cases it can upload file successfully with its path. but to download that file by user it doesnot work. I mean backend works properly for all features. But lacks to download that uploaded file stops by
`javascript:void(0)/*130*/

Answer: i have found the answer of this problem . First run this in terminal.
$ sudo chmod -R 777 /usr/share/ruby-rvm/gems/ruby-1.9.3-p194/gems/ckeditor-3.7.1

follow this path in your computer since i am using linux and my gem file locates here.
 /usr/share/ruby-rvm/gems/ruby-1.9.3-p194/gems/ckeditor-3.7.1/vendor/assets/javascripts/ckeditor/plugins/attachment/dialogs

and open attachement.js file and edit it with the code that u find from tha above link.
click
Now ck editor will works for file attachment also.
Comment: Correct way of doing it is changing:
`gem 'ckeditor'`
to
`gem 'ckeditor', :git => 'git://github.com/netoneko/ckeditor.git'`
in your Gemfile
Answer: Seem like you encounter this bug in CKeditor:
It sugests adding before filter as fix eg:
  # app/model/department.rb

  before_save :fix_ckeditor_attachment_paths

  def fix_ckeditor_attachment_paths
    if self.description.index(/_cke_saved_href/)
      self.description = self.body.gsub(/_cke_saved_href/, 'href')
    end
  end

Comment: Did u use ck editor in rails with mongodb database and it worked fine?
Comment: I just set up sample app and it's works. Here is a github [repo](https://github.com/dmitriybudnik/Rails-CKeditor-Mongoid-and-Paperclip)  for your reference. There was minor glitches seting it up, but I don't think you encounter same issues.
Comment: Thanks for this repo. I  tried it . In Your  ck editor I couldn't find the option to attach zip file. For image i already did. I want to upload zip file from back side and download it from frot side....          try edit this <%= f.cktext_area :notes, :toolbar => 'Easy', :width => 800, :height => 400 %> and click the icon between image upload and flash. That is (Insert attachment) I want to work this function in ck editor.
Comment: I'm new to CKeditor, finding file upload wasn't easy) I think I googled to youtube to actually find it. I used to attach a Pdf file clicking the 'link' and using one of tabs there. I suppose you may attach whenever file you want the same way.
Comment: If u have any idea about using Insert attachment function work properly tthen share me . It is right that giving link also works but in this case your link become rough. It displays all  path like /ckeditor_assets/attachments/503f4fc56d7ab8d360000002/165-edit-multiple.zip?1346326469. It could be better if we can make Download link and after clicking that download link, user can download . Do you have any idea about this?

ckeditor in rails with mongodb


Conditional expection of gamma distribution on sum

Question: I have a process which consists of a number of events and what is known is the timings between the events. What I'm trying to determine is a distribution that allows me to determine a likelyhood that a new sample fits the distibution.
The issue is mainly that if you have lots of samples you can approximate the result using a standard gaussian and use the mean and standard deviation. But if you only have a handful of samples, the gaussian does not accurately represent the situation.
From what I've read it is common to model waiting times using the gamma distribution. Looking at how the process evolves it looks like it matches well. The unknown is the scale parameter, since the shape parameter I think should be the number of samples. What I've worked out so far is that given the timings $X_1 ... X_N$ you can say:
$$ \sum_{n=1}^N X_n \sim \Gamma(N,\theta) $$
($N$ is known and fixed)
However, $\theta$ is unknown, but the maximum likelihood parameter is the average of the $X_i$ (according to wikipedia anyway).
My question is, can I use this to estimate a distribution for $X_i$, that is, since the $X_i$ are independent:
$$ N X_i | \sum_n X_n \sim \Gamma(N, \tfrac{1}{N}\sum_n X_n) $$
Something else I've wondered about. Suppose I do have information about $\theta$, say a distribution. How can I incorporate this into the model?
Edit: Clarified that N is fixed.
Comment: What you're describing above in a round-about way is a Poisson process with rate $\theta$.
Comment: Well, that's true. There is a close relationship the gamma distribution and Poisson processes. But I don't see how that helps me.
Answer: If you have a Poisson process, then each $X_i$ has an exponential distribution (and their sum a Gamma distribution).
You can then use Bayesian methods to look at possible values of $\theta$.  For example, the conjugate prior for an exponential distribution is also a Gamma distribution, which you may find helpful incorporating your prior information and observed data to get a credible interval for $\theta$.
Comment: Aha! That's a good tip for the conjugate prior. I didn't realise that's what it could be used for.
Answer: The reason that wikipedia says $\sum_{i=1}^{N}X_{i}\sim\Gamma(N,\theta)$ is actually because we assume a poisson process. That is, the waiting time for the next event is exponentially distributed $X_{i}\sim EXP(\theta)$. You can prove with the moment generating function that given $X_{i}\sim EXP(\theta)$ for $i=1...N$ IID sample, then $\sum_{i=1}^{N}X_{i}\sim\Gamma(N,\theta)$.
Briefly put, if you assumed the $\sum_{i=1}^{N}X_{i}\sim\Gamma(N,\theta)$ model for your data, then you can also assume $X_{i}\sim EXP(\theta)$. (Meaning that's what they assumed originally...)
One last thing, when you write $NX_{i}|\sum_{i=1}^{N}X_{i}\sim\Gamma(N,\frac{1}{N}\sum_{i=1}^{N}X_{i})$, that is not correct. Instead, $NX_{i}|\sum_{i=1}^{N}X_{i}\sim UNIFORM(0,\sum_{i=1}^{N}X_{i})$. To more or less convince yourself, think that given the value of $\sum_{i=1}^{N}X_{i}=M$, then $NX_{i}$ cannot possibly be greater than $M$.
I hope this helps!
EDIT: I'm wrong about the uniform. See comments.
Comment: Why are you mixing $n$ and $N$? The OP appears to be using $N$ as a fixed, known integer. Also neither $N X_i$ nor $X_i$ are uniformly distributed on $[0,M]$ conditional on the given sum.
Comment: Woops. I wasn't used to typing $N$. I'll change that. However I do believe $X_i$ conditional on the sum is uniform $[0,M/N]$ where $M$ is the sum.
Comment: No, the distribution is not uniform. I think you've likely misunderstood the order-statistic property of the Poisson process. A quick way to check is that $X_i$ definitely has positive probability outside that stated interval for each $i$ conditional on the total sum. You can also check the conditional mean via linearity and see that they don't match.
Comment: Indeed, I don't understand how it can be uniform. The distribution of $X_i$ is indeed exponential. But if you condition it on the sum it has to change, but I don't see how the result can be uniform.
Comment: The conditional distribution of each $X_i$ conditioned on the total sum is the same as the distribution of the *minimum* of $N-1$ i.i.d. uniform $[0,M]$ random variables and so has distribution function $1-(1-x/M)^{N-1}$ on $[0,M]$. Note that this distribution has mean $M/N$, as you should expect. There is a close connection to the beta distribution.
Comment: That's interesting, even if it's not the answer I was hoping for. But why the minimum? Do you have a reference?
Comment: @kleptog, the result, though maybe not explicitly stated as such, is well-known via the characterizations of a Poisson process. Section 2.6 of Durrett, 3rd ed. quickly covers the Poisson process, but leaves this result as an exercise at the end. Resnick's book on stochastic processes has a more complete and general treatment. You can also just derive it directly by transformation of variables since $X_i$ and $\sum_{j\geq 2} X_j$ are independent and have known distributions. If you want, I can post the details in a separate answer because it won't fit here.
Comment: Ah, thank you cardinal! I got confused with another similar formulation... [Here](http://robotics.caltech.edu/~zoran/Research/poisson/node1.html) , slightly before the half of the page was the theorem I thought I was referring to.
Comment: Thanks both of you for the explanations and references. @cardinal: I'm going to see if I can work it out. Unfortunately I can't upvote a comment.


Difference between this and base

Question: I am interested to know the difference between this and base object in C#. What is the best practice when using them?
Answer: this represents the current class instance while base the parent. Example of usage:
public class Parent
{
    public virtual void Foo()
    {
    }
}

public class Child : Parent
{
    // call constructor in the current type
    public Child() : this("abc")
    {
    }

    public Child(string id)
    {
    }

    public override void Foo()
    {
        // call parent method
        base.Foo();
    }
}

Comment: strictly speaking this refers to the current class instance, not the current class type.
Comment: @Adrian, yes good point. Updated my post to take into account.
Answer: The two keywords are very different.

this refers to the current instance (not the "current class"). It can only be used in non-static methods (because in a static method there is no current instance). Calling a method on this will call the method in the same way as it would if you called it on a variable containing the same instance.
base is a keyword that allows inherited method call, i.e. it calls the specified method from the base type. It too can only be used in a non-static method. It is usually used in a virtual method override, but actually can be used to call any method in the base type. It is very different from normal method invocation because it circumvents the normal virtual-method dispatch: it calls the base method directly even if it is virtual.
Answer: Darin is right on. An example may also help. (There wasn't an example when I initially posted. Now there is.)
class Base {

    protected virtual void SayHi() {
        Console.WriteLine("Base says hi!");
    }

}

class Derived : Base {

    protected override void SayHi() {
        Console.WriteLine("Derived says hi!");
    }

    public void DoIt() {
        base.SayHi();
        this.SayHi();
    }
}

The above prints "Base says hi!" followed by "Derived says hi!"
Answer: "this" keyword points to the address of current object. we can use "this" keyword to represent current object (of current class).
Where as "base" keyword represent to "Parent class"
So if you want to use/call function of parent class you can use "base" Keyword.
base is very useful in function overriding to call function of parent class.
Comment: Method overriding* they are inside class and not every method returns value(to get called function).
Answer: this refers to any object that is currently being used. Base refers to a base class generally speaking.
If the object is of the base then in that case this can refer to the base object also.
Answer: this refers to the current class instance.
base refers to the base class of the current instance, that is, the class from which it is derived.  If the current class is not explicitly derived from anything base will refer to the System.Object class (I think).
Answer: lets say you have code like this
class B extends A {

    public B () {
        // this will refer to the current object of class B
        // base will refer to class A
    }

}

Note: The syntax of code is in java but it is self explanatory.
Answer: base - is used to access members of the base class from within a derived class
this - refers to the current instance of the class and inherited
class BaseClass
{
    public string BaseAttr { get; set; }
}
class A : BaseClass
{
    public string Attr { get; set; }
    public void Method()
    {
        this.Attr = "ok";
        this.BaseAttr = "base ok";
        base.BaseAttr = "ok";
        base.Attr = "unavailable"; //!
    }
}

Answer: If you use this.function() in a class, the will get an error due to stackoverflow.
Comment: What language do you mean? This is not always the case. This error can usually occur when creating from the same object inside the constructor in C#.

Difference between this and base


How to remove 'NA' in lm summary ouput

Question: The data I am working with is found here
 http://www.stat.ucla.edu/projects/datasets/
It is the twins data and i downloaded the stata file.
I am performing multiple regression and this is what i have
library(foreign)
twin.data=read.dta("twins.dta")

attach(twin.data)
head(twin.data)
twin.data=na.omit(twin.data)
m1=lm(dlhrwage~deduc1+age+agesq+hrwageh+whiteh+maleh+educh+hrwagel+whitel+malel+educl+deduc2+dten+dmarried+duncov)
summary(m1)

Call:
lm(formula = dlhrwage ~ deduc1 + age + agesq + hrwageh + whiteh +
maleh + educh + hrwagel + whitel + malel + educl + deduc2 +
dten + dmarried + duncov)

 Residuals:
 Min       1Q   Median       3Q      Max
-0.66072 -0.18017 -0.04059  0.11919  1.04205

 Coefficients: (2 not defined because of singularities)
          Estimate Std. Error t value Pr(>|t|)
(Intercept)  6.087e-01  3.690e-01   1.650 0.101391
deduc1       4.005e-02  1.896e-02   2.112 0.036522 *
age         -1.355e-02  1.560e-02  -0.869 0.386628
agesq        9.995e-05  1.932e-04   0.517 0.605846
hrwageh      4.521e-02  3.183e-03  14.204  < 2e-16 ***
whiteh      -1.322e-01  1.946e-01  -0.679 0.498151
maleh       -3.259e-02  5.192e-02  -0.628 0.531299
educh       -2.886e-02  1.370e-02  -2.107 0.037006 *
hrwagel     -3.239e-02  2.746e-03 -11.798  < 2e-16 ***
whitel       1.754e-01  2.014e-01   0.871 0.385267
malel               NA         NA      NA       NA
educl               NA         NA      NA       NA
deduc2       1.505e-02  1.656e-02   0.909 0.365160
dten         1.476e-02  3.741e-03   3.947 0.000128 ***
dmarried     4.486e-02  4.878e-02   0.920 0.359483
duncov      -1.575e-02  5.399e-02  -0.292 0.770992
---
Signif. codes:  0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1

Residual standard error: 0.2977 on 133 degrees of freedom
(36 observations deleted due to missingness)
Multiple R-squared:  0.7626,    Adjusted R-squared:  0.7394
F-statistic: 32.86 on 13 and 133 DF,  p-value: < 2.2e-16

The issue here is the 'NA' showing up for both malel and educ1
MALEL is 1 if twin 1 is male, 0 otherwise. (categorical)
EDUCL is Self-reported education (in years) of twin 1. (numerical)
how do i deal with this?
output of malel is
 malel
  [1] 0 0 0 1 1 0 0 0 1 0 1 1 0 0 0 0 0 1 1 1 0 0 0 1 1 1 0 0 0 1 1 1 1 1 1 1 1 1 0
 [40] 1 0 0 1 0 0 0 1 0 1 1 1 1 1 1 1 1 1 1 1 0 0 0 0 1 1 0 1 1 0 0 0 0 0 0 1 0 0 0
[79] 0 0 0 1 1 1 0 0 1 1 1 1 1 0 0 0 0 0 0 0 1 1 1 1 1 1 0 1 0 1 1 1 1 1 1 1  0 1 1
[118] 0 1 0 0 1 0 1 1 1 0 0 0 0 1 1 0 0 0 1 0 1 0 0 0 0 0 1 1 0 1 0 1 0 0 0 0 0 0 1
[157] 0 0 1 0 0 0 1 1 0 1 1 0 0 1 0 0 0 0 0 0 0 0 0 1 0 0 0

output of educl is
> educl
  [1] 16 10 12 12 14 14 15 14 14 12 13 12 12 19 12 14 16 12 12 12 12 16 12 14 14 12
 [27] 12 14 12 20 12 16 12 11 12 18 18 16 12 14 16 12 16 18 16 13 15 17 16 12 20 14
 [53] 14 12 13 19 13 13 18 16 13 14 18 16 13 12  8 18 14 13 15 16 16 16 14 19 16 12
 [79] 14 12 15 12 12 16 13 16 10 13 12 12 14 12 14 14 16 14 16 12 18 12 16 16 13 16
[105] 12 14 14 16 12 14 16 15 12 13 14 16 15 13 15 10 12 18 12 16 14 14 12 13 15 12
[131] 20 12 14 14 16 16 13 15 16 14 16 12 12 12 12 12 16 12 18 12 12 15 12 12 15 14
[157] 12 12 12 12 12 13 13 13 16 12 13 13 16 18 12 16 10 13 12 12 12 14 12 16 12 16
[183] 16

Comment: Your output gives you a hint: "2 singularities". Could you check whether malel and educl aren't all the same value, or if one of the other contains precisely the same information?
Comment: @iws they arent the same value
Answer: The problem here is that malel and educl are linear combinations of other predictors.
You can see that $malel=maleh$:
> with(twin.data,MALEL-MALEH)
  [1] 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
 [38] 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
 [75] 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
[112] 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
[149] 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0

And that $educl=educh-deduc1$:
> with(twin.data,EDUCL-(EDUCH-DEDUC1))
  [1] 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
 [38] 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
 [75] 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
[112] 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
[149] 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0

When predictors are not linearly independent some parameters are undefined. This can only be solved by dropping redundant predictors until all predictors are linearly independent.
And just as and end note: the way to find out linear combinations has been fitting a linear model with the suspected variable as response: summary(lm(EDUCL~.-DLHRWAGE,data=twin.data))

Edit about how to "solve" the problem, after comments:
I'll put an example of the same problem.
Once a herdsman wanted to count the number of cows in his herd. He supposed he could do it by counting numbers of heads, feet and ears in the herd. He tried performing a regression analysis and got parameters 1 for heads and NA for ears and feet. That is, he could count cows just by counting heads.
However, he decided that dropping redundant predictors was a problem and asked for advice to a neighbour who happened to be a mathematician and gave him the method he was looking for: sum the number of heads, feet and ears in the herd and divide the sum by 7 to get the number of cows.
Anyway, please noticed that adding redundant variables hasn't changed the model - it's predictions are exactly the same. The mathematician just made it more complicated.
Therefore, dropping exactly redundant variables is not a problem. It's just sanitising the data.
The problem that ridge regression and Lasso are created to face is collinearity, and it's a different one, because on collinearity redundancy is not exact. Here ridge regression - if it worked - would just be a way to find one of the many infinite estimation of parameters, and not necessarily the best one because ridge regression doesn't shrink parameters to zero. Maybe lasso could drop automatically the redundant parameters because it does shrink parameters to zero.
However, that isn't better than what already does lm function in R: dropping predictors by returning NA as parameter estimate.
Comment: @MatthewDrury Would ridge regression also work in this situation, where Pere rightly showed (a combination of two) other predictors contain ***exactly*** the same information?
Comment: Thanks you! i did a correlation matrix and found these predictors to have high correlations with those they are a linear combination of.
Comment: @ollypop Not exactly. $malel$ and $maleh$ have correlation 1, but $educl$ is not highly correlated with $educh$ and $deduc1$. You can try `with(twin.data,cor(data.frame(MALEL,MALEH,EDUCL,EDUCH,DEDUC1)))`. Moreover, don't miss this problem with collinearity.
Comment: Dropping predictors is not the only solution! The user could also use ridge regression for example.
Comment: Yes, I believe it would.

How to remove 'NA' in lm summary ouput


How does setBackOffMultiplier(double backOffMultiplier) in ActiveMQ work

Question: I am writing an application using activemq where I am using the redelivery policy to redeliver the messages. I am using the ActiveMQ's ExponentialBackOff concept.
My question is how does this ExponentialBackOff/setBackOffMultiplier work.
For example in my case I want to redeliver the message till the message expiration time, which is 15 minutes.I want to try to redeliver 10 times within 15 minutes.But ExponentialBackOff makes the message to redeliver beyond the 15 minutes expiry time of the message i.e. the message to be redelivered is still in the pending state even after the expiration time which is 15 minutes.
Why is this? I am kind of confused with this behavior. The redelivery policy I am using is as below.
RedeliveryPolicy queuePolicy = new RedeliveryPolicy();
queuePolicy.setInitialRedeliveryDelay(0);
queuePolicy.setBackOffMultiplier(3);
queuePolicy.setUseExponentialBackOff(true);
queuePolicy.setMaximumRedeliveries(10);

Answer: with this RedeliveryPolicy config, the RedeliveryPolicy will make attempts after each time waiting below :
after 1s
after 3s
9s
27s
81s
243s
729s
2187s
6561s
19683s

as you see like this attempts are executed after hours and in the meantime you see messages state is pending.
to prevent these long periods maybe you want to set the maximumRedeliveryDelay=300000L (5 minutes).
Note that

Once a message's redelivery attempts exceeds the maximumRedeliveries configured for the Redelivery Policy, a "Poison ack" is sent back to the broker letting him know that the message was considered a poison pill. The Broker then takes the message and sends it to a Dead Letter Queue so that it can be analyzed later on.

you need to adapt your RedeliveryPolicy because the message is pending as long as maximumRedeliveries is not exceeded.
http://activemq.apache.org/message-redelivery-and-dlq-handling.html
Comment: But the initial delay was 0s. Why it is reset to the default value(1000ms, i.e. 1s) in your answer?


Program that determines if random number is divisible by user input

Question: The user may only enter a number between 1 and 15, so if the input is out of
range, output an error and 'return' out of the function. If the input is good,
then proceed.
Create a loop that generates 10 random numbers between 1 and 100.
I know my javascript is incorrect, I'm stuck atm.

<title></title>

Loop Practice

<form>

Enter a number

<input type="text" id="usernum" />

<input type="button" value="Go For It!" onClick="loopNums()" />

</form>

Comment: Paste the code into your question.  Fiddle links are for demonstrations, not code archiving.
Comment: Open your console, you'll find an error message...
Answer: Take a look at YOUR UPDATED FIDDLE:
function loopNums() {
    var usernum = parseInt(document.getElementById("usernum").value);
    var msg = ""; // "" is the NULL string
    var sum = 0;

    if (usernum < 1 || usernum > 15) {
        msg = "Enter a number between 1 and 15";
    } else {
        for (var i = 0; i < 10; i++) {
            var rdnNumber = Math.floor(Math.random() * ( 1 + 100 - usernum )) + usernum;

            if (rdnNumber % usernum === 0)
                msg += "
Number generated: " + rdnNumber + ". It is divisible by " + usernum + "!
";
            else
                msg += "
Number generated: " + rdnNumber + ". It is not divisible by " + usernum + "!
";
        }
    }

    document.getElementById("results").innerHTML = msg;
}

Comment: I find it remarkable that you figured this out so fast. I personally thought this assignment was very difficult, even after doing a few other loop assignments in class. I even looked at the codes for help and comparison, but I was getting nowhere.
Comment: Question. When you increment i, how come you set the 2nd statement to <10?
Comment: Sorry, I didn't understand your question.
Comment: for( var i = 0; i < 10; i++ ) {  How did you know to use i < 10 for the second statement>? Is that correct?
Comment: You said: "Create a loop that generates 10 random numbers between 1 and 100". If you need to generate 10 random numbers, you need to make 10 iterations. Sorry, I still can't figure out what you're asking.
Comment: Makes perfect sense. You answered my question. Thanks.


Netbeans 8.2 code completion for CSS font-family

Question: I am using Netbeans 8.2 and finding it generally great... however, when coding CSS font-family there is a very limited code completion list (sans-serif, serif, etc.). I have to fully type Arial, Helvetica, sans-serif;. Am I missing something? I have only the HTML5/PHP install.
If using Visual Studio Code the code completion for font-family is working.
Thanks in advance for any light you can shed on this.
Answer:
Am I missing something?

No. I have a full install of NetBeans and get the same result as you.

If using Visual Studio Code the code completion for font-family is
  working.

Well that depends on what you mean by "is working"...
A font-family name can be a family-name or a generic-family.
The generic-family names are formally defined ("serif", "sans-serif", "cursive", "fantasy", "monospace"), and those are provided as options in NetBeans with code completion:

However, family-name is defined as "the name of a font family of choice", meaning you pick a font that you want your web page(s) to use. Given that there are thousands of available fonts, NetBeans cannot know what specific fonts to provide during code completion for font-family. It has no idea what operating system or browser your application is going to use (and you may not either). And even if NetBeans did know the target environment, it would still not be able to provide a guaranteed list of safe fonts during code completion.
Of course some fonts are more popular than others so I suppose you could raise a bug report with NetBeans suggesting that they offer some additional font names on code completion based on popularity, but the process would be very subjective, and different people would would come up with a different lists.
I also checked what Eclipse and Intellij IDEA do for code completion for font-family. Eclipse is the same as NetBeans, offering only the generic-family names, but Itellij IDEA offers a huge list of fonts:

I am running on Windows 10 and it looks like Intellij IDEA is loading up all the names it finds in C:\Windows\Fonts. Perhaps that is what you would like NetBeans to do as well, but be mindful that selecting fonts from that list will not mean that the font will necessarily be available when your application runs in a browser of the user's choice on Android or macOS or iOS or Linux or some different version of Windows.
My own view is that NetBeans and Eclipse are doing the right thing, forcing you to think about what family-name(s) you want to specify, but others may feel differently.


How to override text field widget form in Drupal 8

Question: In my project I am using maxlength module to display the message like
'Content limited to 100 characters, remaining: 20'. The module using the hook 'hook_field_widget_third_party_settings_form' and provide textboxes to add length size and count down message.
I want to alter this count down message for all the fields by using my own custom module. Please help on this ?
Answer: You can create you own widget for textfield you will use in your forms each time you need :
<code><?php

namespace Drupal\your_module\Plugin\Field\FieldWidget;

use Drupal\Core\Field\FieldItemListInterface;
use Drupal\Core\Field\Plugin\Field\FieldWidget\StringTextareaWidget;
use Drupal\Core\Form\FormStateInterface;

/**
 * Plugin implementation of the 'your_widget_widget' widget.
 *
 * @FieldWidget(
 *   id = "your_module",
 *   label = @Translation("Your widget name"),
 *   field_types = {
 *     "string"
 *   }
 * )
 */
class YourWidget extends StringTextfieldWidget {

  /**
   * {@inheritdoc}
   */
  public function formElement(FieldItemListInterface $items, $delta, array $element, array &$form, FormStateInterface $form_state) {
    $element['value'] = $element + [
      '#type' => 'textfield',
      '#default_value' => $items[$delta]->value,
      '#placeholder' => $this->getSetting('placeholder'),
      '#maxlength' => $this->getFieldSetting('max_length'),
      '#attributes' => [
        'class' => ['js-text-full', 'text-full'],
      ],
    ];

    return $element;
  }

}
</code>
You probably have to override settingsForm() with your maxlength settings.
You can do this for each widget type (textarea...)
Note that you can generate skeleton with this drupal command :
<code>$ drupal generate:plugin:fieldwidget
$ drupal gpfw
</code>


regular expression for phone number written with letters

Question: I have a regexp which matches phone numbers
<code>(((\d).{0,5}){7})
</code>
but now I want a regular expresion which matches a phone number written with alpha characters, like this :
<code>nueve nueve tres uno cinco cero tres cinco cinco siete
</code>
Comment: just a bit of advice - people are more likely to help you out if you are likely to help them out in return - you have many questions asked which do not have a selected answer, and people might be deterred from spending time answering with very little chance of reward
Answer: My guess is that you need this for some kind of form where you don't want the users exchanging phone contact details. Maybe they have to pay a subscription fee to be able to contact the other users of the service (by phone). Some users will sometimes try to put this info into a message by putting it in strange formats (numbers as words). Is this assumption correct?
If so, then i'm not sure regex is your best solution for this. You would have to do something like this:
<code>\b(zero|one|two|three|four|five|six|seven|eight|nine)\b
</code>
You could then say that if it matches, then the message is invalid. Big problem with that though is that the user could simply enter the numbers in a different language, or with miss-spelt but easily understandable words - or they could add spaces (or any kind of punctuation) between each letter (there are many ways around this).
You might be better off by doing some kind of fuzzy matching that returns a rank value (Levenshtein distance) that says how likely it is that the user has entered a phone number in the message. You then have a threashold for that rank which if exceeded causes it to fail validation. This is much more complicated than basic regex though. Here are a few links you can check for more info:

Fuzzy matching (wiki)
Levenshtein distance
An article on using Levenshtein distance in C#


timeChange() function returns with a yellow warning. What does it mean or simply how to fix it? Pine Script V5

Question: isNewPeriod = anchor == "Earnings" ? new_earnings :
 anchor == "Dividends" ? new_dividends :
 anchor == "Splits" ? new_split :
 na(src[1]) ? true :
 anchor == "Session" ? timeChange("D") :
 anchor == "Week" ? timeChange("W") :
 anchor == "Month" ? timeChange("M") :
 anchor == "Quarter" ? timeChange("3M") :
 anchor == "Year" ? timeChange("12M") :
 anchor == "Decade" ? timeChange("12M") and year % 10 == 0 :
 anchor == "Century" ? timeChange("12M") and year % 100 == 0 :
 false

Warning is: The function 'timeChange' should be called on each calculation for consistency. It is recommended to extract the call from the ternary operator or from the scope.
The interesting thing is: the PineScript Manual doesn't even know this timechange() function, neither V4 nor V5.
Answer: So, by calling that functions within the ternary operators, you are breaking the history and consistency. Not all those functions will be called on each execution.
If you want to fix the warning, use those functions in the global scope, assign their results to a variable and use those variables in the ternary operator instead.


How does a flutist maintain a grip on the flute when the stops are open?

Question: Per title, how does a flutist maintain a grip on the flute when the stops are open?
If the note requires holding down the stops, I would think that grip is between the closed fingers and the thumb, but if all the stops are open (or the note otherwise requires all fingers to be lifted), then how can the flutist maintain a grip on the flute?
(PS to readers in the UK: please don't change my spelling of flutist, I am using the American spelling)
Comment: I apologise unreservedly. Didn't know you had your own spelling over the pond.
Comment: I think both terms are interchangeable?
Answer: The support of the flute is primarily a balance between the lip plate as it contacts your face and the rest of your fingers on the keys, using the heel of the first finger of your left hand as a fulcrum.
One of the "key" things to understand about this is that there are no notes on the flute with a completely open fingering. The right hand pinky rests on a lever which opens a key when the lever is depressed. This means the "resting state" of your fingers involves depressing the right hand pinky key, which is enough to keep the flute in place against the other two balance points. When the right hand pinky is lifted for a fingering, there are enough other keys depressed that the instrument will stay steady.
Comment: A responsible textbook answer, but what about when you hold the flute away from your face? I was always taught that you only needed to fingers to hold a flute: the right pinky and the left thumb.
Comment: @jjmusicnotes The right pinky isn't the only finger with a "resting state" that depresses the keys. The left hand first finger and thumb both rest on keys that close tone holes on the instrument, and this, with the addition of the heel of the 1st finger, is enough to grasp the instrument (though not enough to counterbalance the lip plate). If one is not playing, you can also just close some of the other keys on either hand to get a grip--this is enough to hold the instrument securely with either hand alone.
Comment: One thing I don't have a clear answer to is if the balance/hold on your flute should be impervious to what your fingers are doing, or should shift depending on which fingers are where? e.g. Playing C4 or C#4 is that what I should be doing all the time or can I use my other fingers for an easier grip when they are available, at the risk the flute moves as I cahnge fingerings?
Comment: @Mr.Boy Whenever the flute is being played, it is being stabilized by one or more fingers on keys in addition to the left hand heel and lip plate. So naturally, this will shift based on the note you're playing, but at any point, any one finger will do.
Comment: You shouldn't need any **extra** fingers to stabilize _beyond what are called for in the note fingering_. If the flute is moving between note changes, you likely just need to practice that change until it is smooth and quick. Finger movements should not be exaggerated.
Comment: So my lips and thumbs are basically what holds it stable regardless what notes I play?
Comment: Reread my comment--I added some formatting that may clarify.
Answer: Per a tutorial on Youtube, "How to Hold the Flute" (by OnlineBandTeacher):

...hold the flute with your right pinky, right thumb and left thumb...

You can see him demonstrate this right around 4:05 in the video (though, it looks like he is holding it with both thumbs and both pinkies).
Comment: But your right pinkie is not always pressing a key. Only your left index finger and right thumb are constantly touching the flute (and your mouth), no?
Answer: If the flute tends to roll inward, toward you, when you have most fingers raised, that is probably due to the heavy key mechanism on top of the flute being tilted too much toward you.  Roll the flute out so as to balance the heavy part more toward the top of the flute as you hold it.  Since you'll have to adapt other aspects of your embouchure to compensate for rolling the flute out more, you may have to make this change by small degrees.


Can the rearrangement inequality be applied to a convergent series?

Question: I recently learned about the rearrangement inequality and was wondering whether it could be applied to convergent series. With that I mean that if:
$$\sum_{i=1}^{\infty}a_ib_i$$
is a convergent series with $a_1\ge a_2\ldots\ge a_n$ and $b_1>b_2\ldots>b_n$ for all $n\in\mathbb{N}$, that for every bijection $\sigma:\Bbb{N}\to\Bbb{N}$ we have:
$$\sum_{i=1}^{\infty}a_ib_i\ge\sum_{i=1}^{\infty}a_ib_{\sigma(i)}$$
I was looking at the proof of the inequality at wikipedia and I'm pretty sure there still is an upper bound, since both series are convergent. The rest of the proof also seems to work, though I'm not sure.
Answer: The finite version of the rearrangement inequality almost tells us that $$\sum_{i=1}^n a_i b_i \ge \sum_{i=1}^n a_i b_{\sigma(i)}$$ for any $n>0$. Because $\sigma$ restricted to $[n] := \{1,2,\dots,n\}$ is not necessarily a bijection from $[n]$ to $[n]$, we can't apply the rearrangement inequality directly. But just define $\tau : [n] \to [n]$ by letting $\tau(i) = \sigma(i)$ whenever $\sigma(i) \le n$ and choosing an unused value of $[n]$ for $\tau(i)$ whenever $\sigma(i) > n$. Then $$\sum_{i=1}^n a_i b_i \ge \sum_{i=1}^n a_i b_{\tau(i)}$$ by the rearrangement inequality, and $a_i b_{\tau(i)} \ge a_i b_{\sigma(i)}$ for all $i$, giving us the inequality we actually want.
From here, we're done, since if the inequality holds for all partial sums then it holds for the infinite sum as well.


Existe uma maneira de usar Processamento de Linguagem Natural (NLP) pra transformar strings em inteiros?

Question: Vi alguns exemplos de códigos pra transformar strings como, por exemplo, "quatro" em um inteiro 4, mas era sempre bastante manual. Tem alguma forma mais automática de fazer isso usando NLP?
Uma coisa que notei quando fiz o teste abaixo foi que o spacyreconhece tanto "quatro" quanto "4" como números, o que já é um bom começo, mas tem como usar isso pra fazer a transformação de um tipo para o outro? Eu não entendo muito de processamento de linguagem natural, então não sei exatamente qual o nome da técnica que seria responsável por isso.
nlp = spacy.load("pt")

doc = nlp("quatro vídeos")
for token in doc:
    print(token.text, token.pos_, token.dep_)
# retorna
# quatro NUM nummod
# vídeos SYM ROOT

doc = nlp("4 vídeos")
for token in doc:
    print(token.text, token.pos_, token.dep_)
# retorna
# 4 NUM nummod
# vídeos SYM ROOT

Obrigada!
Comment: Uma forma "mais robusta" e "mais consistente" pode ter - mas "mais automática" eu duvido  - NLP e outras técnicas vão envolver cofiguração e parametrizações que sempre vão ser mais complexas odo que um match com dicionário `{'zero': 0, 'um': 1, ...}` A leitura de números maiores escritos por exenso ("dois mil cento e setenta e três"), acho que sim, pode ser feita de forma mais simples (automatica) com NLP do que com uma heuristica comum só com `if` e `dicionários`. Mas para um único  dígito, certamente não vai ser a opção mais simples (embora possa ser melhor por vários outros motivos)
Comment: entendi. o que eu fiz pra resolver meu problema foi justamente criar um dicionário, mas eu teria que ficar infinitamente digitando pra conseguir cobrir todos os casos possíveis. você pode me dar um exemplo dessas técnicas mais consistentes que de fato usam NLP?
Answer: não acredito que seja utilizado NLP para resolver este problema. As principais utilizações de NLP são para tradução de texto, geração de texto, geração de legenda para imagens... Atualmente, para resolver esses problemas utiliza-se Redes Neurais Recorrentes (RNN), que são redes neurais profundas que possuem um custo alto para serem treinadas.
Acredito que a forma mais simples de resolver esse problema é realmente utilizar um dicionário. Neste link existem vários exemplos de código em python que resolvem o problema. Você só vai precisar traduzir as palavras do dicionário para o português.
Espero ter ajudado, caso tenha alguma dúvida sobre aplicações de NLP pode perguntar :)


Constructing a tree from a list of edges: missing Leaf nodes

Question: I wrote the below code to construct a tree with given vertex given a list of connections between vertices.
type Connection = (Int,Int)
data Tree = Leaf Int | Node Int [Tree] deriving (Eq,Read,Show)

makeTree :: Int -> [Connection] -> Tree
makeTree x [] = Leaf x
makeTree indx connections =  Node indx otherTrees where
  otherTrees = [makeTree i cx | i <- directConnections, let cx = removeConnectionsTo indx connections]
  directConnections = map (\(x,y) -> if (x == indx) then y else x) $ filter (\(x,y) -> x == indx || y   == indx) connections

removeConnectionsTo :: Int -> [Connection] -> [Connection]
removeConnectionsTo indx = filter (\(x,y) ->    x /= indx && y /= indx)

For some reason, the inputs below give me surprisingly different results:
makeTree 1 [(1,2),(1,3)] gives me Node 1 [Leaf 2,Leaf 3]
makeTree 1 [(1,2),(1,5),(2,3),(2,4),(5,6),(5,7)] gives me Node 1 [Node 2 [Node 3 [],Node 4 []],Node 5 [Node 6 [],Node 7 []]]
I am running GHCi, version 7.4.1 on OS X 10.8.2.
I don't understand why I get Leaf twice in the first example (correct) but node with empty subtree lists in the second example (incorrect).
Comment: What results were you expecting?
Comment: The second answer should have contained "Leaf 3" instead of "Node 3 []" etc.
Comment: I'm downvoting this question because the title is unhelpful and the content reads a bit like "please fix my code" without any clear evidence of investigation etc.
Comment: @BenMillwood : Improved title and question now.
Answer: A quick fix would be to just check if otherTrees is empty before deciding whether to build a Leaf or a Node, e.g.
makeTree indx connections
  | null otherTrees = Leaf indx
  | otherwise       = Node indx otherTrees
  where ...

To understand what is happening here, let's add a little instrumentation:
import Debug.Trace

makeTree :: Int -> [Connection] -> Tree
makeTree ix cs | traceShow (ix, cs) False = undefined
makeTree x [] = ... -- leave rest of the function as before

Now load it up into GHCi, and let's see what the recursive calls are:
> import Control.DeepSeq
> (show $ makeTree 1 [(1,2),(1,5),(2,3),(2,4),(5,6),(5,7)]) `deepseq` ()
(1,[(1,2),(1,5),(2,3),(2,4),(5,6),(5,7)])
(2,[(2,3),(2,4),(5,6),(5,7)])
(3,[(5,6),(5,7)])
(4,[(5,6),(5,7)])
(5,[(2,3),(2,4),(5,6),(5,7)])
(6,[(2,3),(2,4)])
(7,[(2,3),(2,4)])
()

As you can see, the list in the second argument is not empty which is why it doesn't match the first case of your function, so you'll either need to add some additional checks as in my example, or make sure that you filter out the rest of the connections.
Comment: Arrgh, took me awhile to figure out! Thanks for your info about DeepSeq and trace - they will come in handy :)
Comment: Your solution worked, but I still can't figure out why mine did not. When invoking a function, the function declarations are selected in order of declaration, so the `makeTree x [] = Leaf x` should have matched first, isn't it?
Comment: It doesn't match, because the list in the second argument isn't empty. The only connections that get removed from the list on the path down to a node are the ones that mention its ancestors, so e.g. when you get to `makeTree 7`, `connections` still has `[(2, 3), (2, 4)]` in it.


In how many ways can $7$ items be selected from $14$ items of $3$ types so that there is at least one of each type?

Question: There are 14 items of 3 types: 2 of the first type, 4 of the second type and 8 of the third type. You must select 7 items so that there is at least one item of each type.
My solution
$3! \cdot {11 \choose 4} = 330 \cdot 6 = 1980$
Comment: Why $3!$? Explain the logic there.
Comment: This is far too high.  There are fewer than $10$  ways to do it.  Among other things, you appear to be ignoring the number of available items of each type.
Comment: @Deepak  As a quick way to do it, note that you must choose either $1$ or $2$ of type one, and one of $\{1,2,3,4\}$ of type two.  All choices lead to valid triples and type three items present no difficulty. There are $2\times 4=8$ ways to do that, and that choice determines the triple.
Comment: @Deepak  Right. And because there are enough type three items so that you can ignore the cap.  Should say:  I am assuming that all objects of a given type are indistinguishable.  If that is not the case, then for each of my $8$ cases you'll need to consider the number of ways to select within a single type.
Comment: @lulu Thanks. Should've written some working down.
Comment: Are the items of the same type distinguishable?
Comment: @lulu Really? My answer is higher than the OP's. Am I making a mistake here?
Comment: @Deepak  Yes.  You are badly overcounting.  If, say, your selection has $5$ of type three, then you count it at least $5$ times.
Comment: @lulu Let me think through this, but I'll delete my answer first to be safe.
Comment: @lulu Ah OK, because you're guaranteed to get an item of the third type. Thanks.
Comment: @user Items of the same type indistinguishable
Answer: Your problem is equivalent to finding the number of integral solutions to the equation
$$ a + b + c = 7 ~\text{ s.t. }\\
1 \le a \le 2 \\
1 \le b \le 4 \\
1 \le c \le 8$$
Change the variables $a' = a - 1, b' = b - 1, c' = c - 1$
$$ a' + b' + c' = 4 ~\text{ s.t. }\\
0 \le a' \le 1 \\
0 \le b' \le 3 \\
0 \le c' \le 7$$
Note that since $a', b', c'$ are non-negative, the last contraint is the same as $0 \le c' \le 4$
The number of solutions to this can be found out by simple inclusion-exclusion
$$ \binom{6}{2} - \binom{4}{2} - \binom{2}{2} = 15 - 6 - 1 = 8 $$
$\displaystyle\binom{6}{2}$ is the number of non-negative integral solutions to $a' + b' + c' = 4$
$\displaystyle\binom{4}{2}$ is the number of non-negative integral solutions to $a' + b' + c' = 4$ with $a' > 1$
$\displaystyle\binom{2}{2}$ is the number of non-negative integral solutions to $a' + b' + c' = 4$ with $b' > 3$
Note that any other exclusion case has zero possibilities because if $c' > 4$, the sum of $a', b', c'$ cannot be $4$
The same is true when both $a' > 1$ and $b' > 3$
Comment: @user The number of non-negative integral solutions to $a′+b′+c′=4$ with $a'>1$ (or $a'\ge2$) is the same as the number of non-negative integral solutions to $a''+b′+c′=2$ where $a'' = a '- 2$, which we know is $\binom{2+3-1}{3-1} = \binom{4}{2}$
Comment: What kind of formula did you use to obtain $\binom42$ and $\binom22$?
Answer: Here's a solution under the assumption that items of the same type are instead distinguishable.
Without the restriction of at least one of each type, there are $$\binom{2+4+8}{7}=\binom{14}{7}=3432$$ choices.
Applying the principle of inclusion-exclusion yields
\begin{align}
&\binom{2+4+8}{7}
-\left[\binom{2}{0}\binom{4+8}{7}+\binom{4}{0}\binom{2+8}{7}\right]
+ \binom{2}{0}\binom{4}{0}\binom{8}{7} \\
&= 3432
-\left[792+120\right]
+8 \\
&= 2528.
\end{align}


How to make UIWebView in the Detail View of a UISplitView change its content when a row in RootView is selected?

Question: I have a UISplitView-based app with a UIWebVIew in the Detail View. I want to make it change its content when user chooses a new row in the table in Root View. I tried like this in DetailViewController:
- (void)setDetailItem:(id)newDetailItem {
extern NSString *rowname;
if (detailItem != newDetailItem) {
    [detailItem release];
    detailItem = [newDetailItem retain];
    // Update the view.
if ([rowname isEqualToString:@"About"])
 [self loadFile:@"About.rtf"];
if ([rowname isEqualToString:@"Square"])
 [self loadFile:@"Square.rtf"];
//And so on with every UITableView element from the RootView
if (popoverController != nil) {
    [popoverController dismissPopoverAnimated:YES];
}
}
}

Help me, please!
Thanks in advance!
Answer: See the videos in chapter 3 on this website: http://www.lynda.com/home/DisplayCourse.aspx?lpk2=65722
Answer: You need a reference to the viewcontroller which contains the webview (your detail view controller) within your rootview controller. when a row is selected, call a method in the webview (detail) controller and pass it a filename, URL, whatever... and it in turn calls the uiwebview method to load the request. Either loadRequest: or loadHTMLString:
docs here
Comment: I managed to do it like in the tutorials and examples on the web. But in the tutorials the UITableView has only one level and I have a two leveled table. That's the problem now
Comment: You need a UINavigationController wrapping your tableview controller, then a table row selection (creates if needed, and...) pushes the new view controller. Just look at any sample source code where there are multiple drill-down tables. It works the same here.


what does this mean? *[class="hide"] in css

Question: What is going on here with this css?
The * and [] are confusing me, I haven't seen it before.
I realise it is to hide but does it mean if I create an element with class="hide" it will hide it?
I can't find anything online to explain it
*[class="hide"] {
        display: none !important;
    }

Comment: .hide{display:none !important;}
Answer: The * is the universal selector that matches a single element of any type. When combined with other selectors, the asterisk can usually be omitted. In your case, you could also just write [class="hide"].
The square brackets [] indicate an attribute selector which is used to match elements that have a certain attribute and value combination. In your case class="hide" is a match by an exact attribute value. So you are looking for elements that have an attribute class which value is exactly hide.
Usually, people will match class attributes using the class selector indicated by a leading dot. So .hide would be a mostly equivalent selector to yours.
There is a differences between .hide and [class="hide"] though: [class="hide"] will only match when hide is the only class of the element. So an element
…
 will be matched by .hide but not [class="hide"]:

.foo {
  color: teal;
}
[class="foo"] {
  background: #EEE;
}

Class and attribute selectors will match here

Only the class selector will match here

In your case, I'm not sure if that's such a good idea since a hide class is usually used to temporarily hide elements. So it's just a class you can add to elements to make it disappear and remove it again to get it back. By having a selector that matches on attribute equality, you are essentially preventing yourself from this toggle-ability, as you will have to actively replace all existing class names.
Answer: 1. *[class="red"] selects all elements with the class name exactly red. It is same as calling [class="red"] ie. the * is redundant.
2. [class*="red"] selects all elements with the class names containing the string red in it.

*[class="red"] {
  color: red
}

[class*='blue'] {
  color: blue;
}

Test 1

Test 2

Test 3

Answer: * is a wild card selector and applies to all elements, e.g. div>* applies to any element that is directly under a div.
The brackets indicate attributes of the elements to match, so this line applies to any element that has a class attribute with value hide, though I think the logical thing would have been to just define the class .hide instead.
https://developer.mozilla.org/en/docs/Web/CSS/Attribute_selectors
Answer: This question may be duplicate with this
*[class="hide"] will select anything with class="hide"


Observable of pipe shareReplay vs. ReplaySubject.observableOf

Question: shareReplay isn't working like I would expect. From the documentation I would expect the following bits of code to be equivalent.
@Injectable( {
    providedIn: 'root'
} )
export class CartService {

    private list: InventoryItem[] = [];
    cart: Observable<ReadonlyArray<Readonly<InventoryItem>>> = of( this.list ).pipe(
        shareReplay( 1 )
    );

    constructor() {}

    addItem( item: InventoryItem ) {
        this.list.push( item );
    }
}

and
@Injectable( {
    providedIn: 'root'
} )
export class CartService {

    private list: InventoryItem[] = [];
    private subject = new ReplaySubject<ReadonlyArray<Readonly<InventoryItem>>>(1);
    cart: Observable<ReadonlyArray<Readonly<InventoryItem>>> = this.subject.asObservable();

    constructor() {}

    addItem( item: InventoryItem ) {
        this.list.push( item );
        this.subject.next(this.list);
    }
}

Yet only the second version works where all subscribers receive the events when addItem(...) is called.
The first example only works in one instance in my root component, but not in any other component where I use a similar syntax.
[matBadge]="(cartService.cart | async)?.length"

I've verified that only one instance of the service is being created, can anyone give me some insight on what's going on in the first piece of code?
Answer: Your examples are not the same.
private list: InventoryItem[] = [];
    cart: Observable<ReadonlyArray<Readonly<InventoryItem>>> = of( this.list ).pipe(
        shareReplay( 1 )
    );

of(this.list) will take current this.list and when you subscribe you get the list but you won't get the list again if you do this.list.push(...). You would have to subscribe again.
On the other hand when you signal change in the list using Subject, your subscribers will get notified again.
So this is critical:
this.subject.next(this.list);

Comment: I see, I had assumed `this.list.push(...)` would trigger observable changes. Instead I only pushed the reference to the list once. The reason my root component worked is it was the only one that wasn't using `OnPush` change detection.


Website loading CSS files that do not exist

Question: Whenever I make changes to files I am hosting for my website, like the CSS files, they never update. Even after deleting the original CSS files everywhere, using Chrome's inspect element still shows that the websites HTML is being styled by the "style.css" file that doesn't exist. The only way I have found around this is by changing the HTML pages to be styled by a "style2.css", and renaming my updated CSS file to "style2".
Is this not insanely weird? Ghost files? I'm not going crazy right?
Comment: Sounds like a caching issue.
Comment: It is usually easier to update your site to be styled by `style.css?version=2`.  Then you don't have to rename the css file, just update the version number in your HTML.
Answer: Try refreshing with CTRL+F5 instead of only F5
This will clear the already cached files like css and js and will reload the updated ones
Let's say you have style.css
with
<code>.body{
background-color:white;
}
</code>
after that you change the same style.css file to
<code>.body{
background-color:black;
}
</code>
sometimes the navigator won't read the new code in css/js
and will load the old ones unless you clear them
This could be your problem, try it and check again
Or you could check out this case : How to force the browser to reload cached CSS and JavaScript files


Prove that for all natural numbers $x$, $y$, $z$, and $w$ that $gcd(x,y)gcd(z,w) | gcd(xz,yw)$.

Question: Prove that for all natural numbers $x$, $y$, $z$, and $w$ that  $gcd(x,y)gcd(z,w) | gcd(xz,yw)$. I established a prime factorization product for each variable and I've tried using GCD's via prime factorizations to prove this but I get stuck when I multiply $gcd(x,y) \times gcd(z,w)$ and I'm not sure what to do with $\prod_{j=1}^{\infty}{p_i^{min(a_i, b_i) + min(c_i, d_i)}}$. Any help is appreciated!
Answer: There are three key facts:
First, $\gcd(a,b)$ divides both $a$ and $b$ as it is a common divisor.
Second, if $a|b$ and $a|c$ then $a|\gcd(b,c)$, by definition of the greatest common divisor.
Third, if $a|b$ and $c|d$ then $ac|bd$, for if $b=ax$ and $d=cy$ , we have $bd=ac(xy).$
Notice that $\gcd(x,y)$ divides $x$ and $y$.
Similarly, $\gcd(z,w)$ divides $z$ and $w$.
Hence, $\gcd(x,y)\gcd(z,w)$ divides $xz$ and $yw$. This implies $\gcd(x,y)\gcd(z,w)|\gcd(xz,yw).$
As for your particular approach, it suffices to observe that the exponent of $p_i$ in the prime factorization of $xz$ is $a_i+c_i$. In particular, this is at least $\min(a_i,b_i)+\min(c_i,d_i)$. This implies $$ \gcd(x,y)\gcd(z,w)=\prod_{j=1}^\infty p_i^{\min(a_i,b_i)+\min(c_i,d_i)}|\prod_{j=1}^\infty p_i^{a_i+c_i}=xz.$$
Similarly, $\gcd(x,y)\gcd(z,w)$ divides $yw$.